I have this code interaction with 2 files, but I am getting a segmentation error in these two functions and I need help figuring out why. fileA.c
passes an int**
to a function in fileB.c
, the int**
serves as an output parameter because I want to make an int array in fileB
and have foo
point to it so I can print it in fileA
. In fileB.c
, I make an array, and set the pointer to it.
size and foo are initialized in another function in a main file. It compiles fine, the output though would be (if size == 10
) :
0 1 2 3 4 5 6 7 8 9
Segmentation fault
In fileA.c
:
void testPointing(int size, int** foo) {
initialize(size, foo);
int i;
for(i = 0; i < size; i++) {
printf("%d ", (*foo)[i]);
}
}
fileB.c
:
void initialize(int size, int** foo) {
int* a;
a = (int*)malloc(size * sizeof(int);
int i;
for(int i = 0; i < size; i++) {
printf("%d ", a[i]);
}
printf("\n\n");
foo = &a;
}
I need help fixing and understanding why I am getting a segmentation fault. Whenever I opt to put the loop located in fileA.c
after
foo = &a
in fileB.c
instead, it compiles and shows a correct output.