Multi-dimensional Array Allocation

耗尽温柔 提交于 2019-12-13 09:05:37

问题


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]
  }


来源:https://stackoverflow.com/questions/13304278/multi-dimensional-array-allocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!