Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to dynamically allocate matrix in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

int** allocateMatrix(int rows, int cols) {
    int** matrix = (int**)malloc(rows * sizeof(int*)); // Allocate rows
    if (matrix == NULL) {
        printf("Memory allocation failed for rows!\n");
        return NULL;
    }

    for (int i = 0; i < rows; i++) {
        matrix[i] = (int*)malloc(cols * sizeof(int)); // Allocate columns
        if (matrix[i] == NULL) {
            printf("Memory allocation failed for row %d!\n", i);
            return NULL;
        }
    }
    return matrix; // Return pointer to the matrix
}

void freeMatrix(int** matrix, int rows) {
    for (int i = 0; i < rows; i++) {
        free(matrix[i]); // Free each row
    }
    free(matrix); // Free the array of pointers
}

void initializeMatrix(int** matrix, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            matrix[i][j] = i * cols + j; 
        }
    }
}

void printMatrix(int** matrix, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%2d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int rows = 3, cols = 4;

    // Allocate memory for the matrix
    int** matrix = allocateMatrix(rows, cols);
    if (matrix == NULL) {
        return 1; // Exit if memory allocation fails
    }

    // Initialize and print the matrix
    initializeMatrix(matrix, rows, cols);
    printMatrix(matrix, rows, cols);

    // Free allocated memory
    freeMatrix(matrix, rows);

    return 0;
}



/*
run:

 0  1  2  3 
 4  5  6  7 
 8  9 10 11 

*/

 



answered Mar 29, 2025 by avibootz

Related questions

2 answers 173 views
1 answer 184 views
184 views asked May 19, 2025 by avibootz
1 answer 58 views
2 answers 154 views
2 answers 320 views
1 answer 138 views
138 views asked May 7, 2021 by avibootz
...