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

AI Thread Summary
The discussion focuses on the dynamic allocation of a 2D array in C using an array of pointers. The code provided successfully allocates memory for both the array of pointers and the actual integer values, with the first malloc statement necessary to create space for the row pointers. The size of a pointer is confirmed to be 8 bytes in a 64-bit environment, which explains the need for the first malloc. The second malloc allocates a contiguous block for the matrix data, and a loop assigns pointers for each row. Proper memory management is emphasized, highlighting the need to free both the integer block and the array of pointers after use.
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!
 

Similar threads

Replies
3
Views
1K
Replies
4
Views
1K
Replies
7
Views
2K
Replies
1
Views
10K
Replies
3
Views
1K
Replies
2
Views
2K
Back
Top