Dynamic allocation of memory to 2 dimensional Array in a Single malloc Call

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • neeru29
    New Member
    • Feb 2009
    • 21

    Dynamic allocation of memory to 2 dimensional Array in a Single malloc Call

    To allocate a 2D array of integers, in such a way that the array elements can be accessed with a[i][j] syntax i.e., should not use pointers to access the values.

    Note: The function should perform only a single malloc call.

    The function declaration is:

    int **alloc_array( int nrows, int ncols);
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Read: http://bytes.com/topic/c/insights/77...rrays-revealed

    Comment

    • neeru29
      New Member
      • Feb 2009
      • 21

      #3
      I had tried with the following statement to allocate memory to 2D array:

      Code:
      arr2D = (int **)malloc(row * sizeof(int *) + row * col * sizeof(int));
      
      for(i = 0; i< row; i++)
      {
       for(j=0; j< col; j++)
       {
        scanf("%d", &a[i][j]); // here the memory segmentation is displayed.
       }
      }
      Please help me out

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Are you sure you can't use two malloc calls to set this up?

        Comment

        • neeru29
          New Member
          • Feb 2009
          • 21

          #5
          i got it by using multiple malloc calls.. i want it by single malloc call

          Comment

          • weaknessforcats
            Recognized Expert Expert
            • Mar 2007
            • 9214

            #6
            Remember, there is no such thing as a 2D array.

            And an int** does not point to a 2D array.

            If you have a 9 element array, the elements are in memory as

            1 2 3 4 5 6 7 8 9

            and you can't tell if this is a [9][1] or a [3][3].

            So when you allocate you allocate the number of elements.

            Let's say you need a [4][6] array of int. That's 24 ints. So allocate 24 ints.

            malloc will return a pointer to the 24 ints.

            Now a [4][6] array is an array of 4 elements where each element is an array of 6 int. Therefore typecast the return from malloc as a pointer to an array of 6 int:

            Code:
            int (*MyArray)[6] = (int(*)[6])malloc(24*sizeof(int));
            You will need a separate variable to hold the 4 which is the number of elements.

            Go back and read that article again. The final example is the one I am talking about here.

            Comment

            Working...