C Programming: Dynamic allocation of 2D arrays using an array of pointers.

Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 3K views
ashwinnarayan
Messages
16
Reaction score
0

Homework Statement


Ok, I'm learning C programming and I'm trying to create a dynamic 2D array. This is the code that seems to work in creating a dyamic array. I found it in a book.

Code:
    //rows and cols are values entered by the user when the program runs.
    int **(matA) = malloc(rows*sizeof(int *));
    
    matA[0] = malloc(rows*cols*sizeof(int));

    for(i=1;i<rows;i++) matA[i] = matA[0] + (i*cols);

My question is: What is the function of the statement sizeof(int *)?

I ran the program with a printf statement to print the value of sizeof(int *) and it came up as 8. I don't understand why this first malloc statement even exists. If I delete the first malloc statement then the code doesn't run.
 
Last edited:
Physics news on Phys.org
Code:
    int **(matA) = malloc(rows*sizeof(int *));
This statement allocates an array of (rows) pointers and stores the pointer to the array of pointers in matA. Apparently you're running in 64-bit mode since the size of a pointer is 8 bytes.

Code:
    matA[0] = malloc(rows*cols*sizeof(int));
This statement allocates a single block of (rows * cols) integers for all of the matrix and stores it in matA[0], the pointer to the first row. The loop stores the pointers for the remaining rows. When your code is done it should free the memory as follows:

Code:
    free(matA[0]);  /* free block of integers */
    free(matA);     /* free array of pointers */
 
Last edited:
Oh! I get it now. I was confused by the two layers of pointers. The initial statement allocates memory for the array of pointers and since the array needs to hold pointers each element needs to have enough memory to store pointers of type (int *).

Thanks!