N
No Such Luck
Hi all:
Below are two pieces of code that basically perform the same task.
Version A produces a segmentation fault, while version B works
correctly. I understand why version B works correctly, but I do not
understand why version A does not work. It seems to me that in Version
A, a pointer to an array of integers is passed as a parameter to
init_array, and whether that pointer is NULL or not, is should be
initialized as a new array of integers.
Can anyone elaborate? Thanks.
---------Version A (Seg Fault)--------
#include <stdio.h>
#include <stdlib.h>
void init_array (int * array, int num)
{
array = (int *)malloc(sizeof(int) * num);
}
int main ()
{
int array_size = 5;
int * array;
init_array(array, array_size);
array[3] = 10; /* This causes a segmentation fault */
return 1;
}
---------Version B (Works Correctly)--------
#include <stdio.h>
#include <stdlib.h>
int * init_array (int num)
{
int * array;
array = (int *)malloc(sizeof(int) * num);
return array;
}
int main ()
{
int array_size = 5;
int * array;
array = init_array(array_size);
array[3] = 10;
return 1;
}
Below are two pieces of code that basically perform the same task.
Version A produces a segmentation fault, while version B works
correctly. I understand why version B works correctly, but I do not
understand why version A does not work. It seems to me that in Version
A, a pointer to an array of integers is passed as a parameter to
init_array, and whether that pointer is NULL or not, is should be
initialized as a new array of integers.
Can anyone elaborate? Thanks.
---------Version A (Seg Fault)--------
#include <stdio.h>
#include <stdlib.h>
void init_array (int * array, int num)
{
array = (int *)malloc(sizeof(int) * num);
}
int main ()
{
int array_size = 5;
int * array;
init_array(array, array_size);
array[3] = 10; /* This causes a segmentation fault */
return 1;
}
---------Version B (Works Correctly)--------
#include <stdio.h>
#include <stdlib.h>
int * init_array (int num)
{
int * array;
array = (int *)malloc(sizeof(int) * num);
return array;
}
int main ()
{
int array_size = 5;
int * array;
array = init_array(array_size);
array[3] = 10;
return 1;
}