Trouble understanding "Double" Pointers.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • livesinabox
    New Member
    • May 2010
    • 4

    Trouble understanding "Double" Pointers.

    I am a student and I am having trouble understanding Dynamic Memory Allocation and the usage of Double Pointers.

    Code:
    int **A
    
    A=(int **)malloc(r1*(sizeof(int*)));
    
    for(i=0;i<r1;i++)
    A[i]=(int *)malloc(sizeof(int)*c1)
    In the above snippet r1 and c1 refer to the number of rows and columns of a matrix A.

    My question : What does the malloc function do here? I know malloc() is used to allocate memory during runtime and the argument(r1*(si zeof(int*)) is supposed to the size of the memory allocated. Does the argument mean r1 x size of int (ie) r1 x 2 (where 2 is the size of an integer in the memory)?

    And what does the coding inside the for loop do? Why is each element being allocated new space again?
    Last edited by Banfa; May 28 '10, 09:20 AM. Reason: Use this slash / for closing tags :-)
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    In line 3 the r1*(sizeof(int* ) is not r1 * the size of int. That is an int *, integer pointer not an int so it is r1 * the size of an integer pointer.

    Line 3 allocates an array of pointers to integer.

    The loop then allocates an array of c1 integers (c1 * sizeof(int))) to each one of the pointers allowing you yo use the point A in a similar fashion to a double indexed array.

    However there are some differences, memory footprint is one. An actual double indexed array has all its memory in a contiguous block, this is not true for this method of allocation using malloc because each of the arrays in the loop is allocated separately and you then have no guarantee that they will be contiguous.

    Comment

    • livesinabox
      New Member
      • May 2010
      • 4

      #3
      That helps! Thank You!

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Take a look at Arrays Revealed.

        You should always check the value returned by malloc to confirm it is not NULL. That is, to make sure malloc succeeded.

        Comment

        Working...