I am absolutely new to C and I tried to initialize a array in a function.
But it doesn't work, because if I want to print the values in the main method I always get a Segmentation fault.
static void array(int *i)
{
int j = 0;
i = (int *) malloc(5 * sizeof (int));
for (j = 0; j < 5; j++) {
i[j] = j;
}
for (j = 0; j < 5; j++) {
printf("Hello: %d\n", i[j]);
}
}
/* Main entry point */
int main(int argc, char *argv[])
{
int j;
int *i = NULL;
array(i);
for (j = 0; j < 5; j++) {
printf("Hello: %d\n", i[j]);
}
return 0;
}
Would be nice if someone could fix the code and could explain how it works.