C: Correctly freeing memory of a multi-dimensional array

后端 未结 5 806
清酒与你
清酒与你 2020-11-28 04:00

Say you have the following ANSI C code that initializes a multi-dimensional array :

int main()
{
      int i, m = 5, n = 20;
      int **a = malloc(m * sizeo         


        
5条回答
  •  [愿得一人]
    2020-11-28 04:58

    I would call malloc() and free() only once:

    #include 
    #include  
    
    int main(void){
      int i, m = 5, n = 20;
      int **a = malloc( m*(sizeof(int*) + n*sizeof(int)) );
    
      //Initialize the arrays
      for( a[0]=(int*)a+m, i=1; i

提交回复
热议问题