Multi-dimensional Array Allocation

2019-09-22 10:28发布

问题:

I am almost a beginner in C and I want to allocate a 2 dimensional array, change it, reallocate it and print it. Both of the answers with the code were useful.Now the code is:

    main()
    {
     int i, j, L , **lp ;
      scanf("%i" , &L );
      lp = calloc(L , sizeof(*lp) );
      for(i=0 ; i<L ; i++)
      lp[i] = calloc( L , sizeof( *(lp[i])) );

      for(i=0 ; i<L ; i++)
      {
          for(j=0 ; j<L ; j++ )
          {
           lp[i][j]=0;
           printf("%i\t" , lp[i][j] );
          }
       printf("\n");
      }
       free( lp );
       return(0);
     }

回答1:

A lot of things are wrong.

1. The for loop

{   for(j=0 , j<0 , j++ )


for (initialization_expression;loop_condition;increment_expression){..}

If any of them is missing, leave them blank, but you do need the semicolons.

Even then j=0;j<0 makes no sense as a condition.

2. Misspelling

You misspelled lp as pl within the second for-loop.

3. main

You did not specify a return type for main. This isn't being reported but is the old-style and shouldn't be used anymore.

4. Dynamic allocation

That isn't the way to allocate a 2-D array dynamically.



回答2:

Many errors here, but as for the allocation you should do like this :

int main()
{
    int i = 0;
    int j = 0;
    int L = 0;
    int **lp = NULL;

    scanf("%i", &L);
    if (!(lp = calloc(L, sizeof(*lp)))) //allocate 1st dimension
        return (0);
    for (i = 0; i < L; i++)
    {
        lp[i] = calloc(L, sizeof(*(lp[i]))); //all 2nd dimensions
    }
    return (0);
}

And don't cast the return of malloc...



回答3:

First of all correct the errors in the for loop. The syntax is wrong. Check variable spellings.

Now for the allocation part. You have allocated memory only for a single dimensional array in your code. The following procedure is to be followed for allocating a 2 dimensional array.

First we need to allocate an array of pointers. And the size of the array is the number of rows. Then we allocate memory for each row of the 2D array. And we assign address of each row (which is essentially a 1D array, hence a pointer) to the pointers we allocated already.

Thus we need a pointer to pointer array initially. And for each pointer to pointer in this array, we assign an array that corresponds to a row in the 2D Array.

You can do is as follows.

int **a;
int size,x;

//--- Obtain size of array in size;

a = calloc(size,sizeof(int *));  //Allocating a row of pointers and assigning to **a 

//for each *a in *a[] (i.e **a), we assign an array of ints.
for(x = 0; x < size; x ++) 
{
  a[x] = calloc(size,sizeof(int)); 
}

Now you can access this array like this:

for(i=0;i<size;i++)
  for(j=0;j<size;j++)
  {
    //do something with a[i][j]
  }