1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Oct 25, 2012 #1
    1. The problem statement, all variables and given/known data
    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 (Text):

        //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: Oct 25, 2012
  2. jcsd
  3. Oct 25, 2012 #2

    rcgldr

    User Avatar
    Homework Helper

    Code (Text):

        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 (Text):

        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 (Text):

        free(matA[0]);  /* free block of integers */
        free(matA);     /* free array of pointers */
     
     
    Last edited: Oct 25, 2012
  4. Oct 26, 2012 #3
    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!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




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