Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how can I use "malloc" for 2d matrix?

0 votes
asked May 28, 2019 by wilques (120 points)
how can I use "malloc" for 2d matrix?

1 Answer

0 votes
answered Jun 22, 2019 by bekulio (180 points)
/******************************************************************************

Welcome to GDB Online.

GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,

C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.

Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/

#include <stdio.h>

#include <stdlib.h>

int main()

{

    unsigned int i, j, nrows = 2;

    unsigned int ncolumns = 3;

    

    unsigned int **array;

    

array = malloc(nrows * sizeof(unsigned int *));

if(array == NULL)

{

fprintf(stderr, "out of memory\n");

return -1;

}

for(i = 0; i < nrows; i++)

{

array[i] = malloc(ncolumns * sizeof(int));

if(array[i] == NULL)

{

fprintf(stderr, "out of memory\n");

return -1;

}

}

array[0][0] = 100;

array[0][1] = 101;

array[0][2] = 102;

array[1][0] = 110;

array[1][2] = 112;

array[1][1] = 111;

for(i = 0; i < nrows; i++)

    for(j = 0; j < ncolumns; j++)

            printf("\nArray[%d][%d] = %d", i, j, array[i][j]);

    return 0;

}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...