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
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.