malloc-ating multidimensional array in function

前端 未结 7 1845
傲寒
傲寒 2020-12-10 22:28

I\'m trying to allocate a 2d array in a C program. It works fine in the main function like this (as explained here):

#include 
#include 

        
7条回答
  •  猫巷女王i
    2020-12-10 23:03

    C is pass by value. And to sum up the error you are doing, this example should be helpful -

    void foo( int *temp )
    {
         temp = malloc(sizeof(int)) ;
         // temp is assigned to point to new location but the actual variable
         // passed from main do not point to the location temp is pointing to.
    
         *temp = 10 ;
    }
    
    int main()
    {
         int *ptr ;
         foo( ptr ) ;
    
         // ptr is still unintialized
         *ptr = 5 ; // Segmentation fault or Undefined behavior
    
         return 0;
    }
    

    So, instead you should do -

    void foo( int **temp )
    {
        *temp = malloc(sizeof (int) );
        // ...
    }
    

    And now call the function as foo(&ptr); in the main() function.

提交回复
热议问题