I am trying to dynamically create an array in a separate function and store some variables inside of that array and I came across the following: how come when I write;
#include <stdio.h> #include <stdlib.h> void foo(int **arr, int N) { *arr = malloc(sizeof(int)); for (int index = 0; index <= 4; index++) { *arr[index] = 1; } } int main() { int *arr; foo(&arr, 5); for (int bar = 0; bar <= 4; bar++) { printf("%d ", arr[bar]); } } I get this output;
exited, segmentation fault However, when I run the following;
#include <stdio.h> #include <stdlib.h> void foo(int **arr, int N) { *arr = malloc(sizeof(int)); } int main() { int *arr; foo(&arr, 5); for (int index = 0; index <= 4; index++) { arr[index] = 1; } for (int bar = 0; bar <= 4; bar++) { printf("%d ", arr[bar]); } } I get this output;
1 1 1 1 1 I am stuck trying to figure out how to fix the first block of code to get it to work, but I seem to have no idea how to do so. Any help would be appreciated in at least understand why a segmentation fault occurs.