I have a simple C code:
int main()
{
int test[10] = {1,2,3,4,5,6,7,8,9,10};
int **ptr = &test;
printf("%d\n", (*ptr)[0]);
return 0;
}
As soon as it reaches the printf
line, it crashes:
Process returned -1073741819 (0xC0000005) execution time : 0.865 s
When compiling the code on Ubuntu, it gives me the warning:
test.c:8:17: warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
int **ptr = &test;
However, if I instead dynamically allocate the memory on the heap, the code works:
int main()
{
int *test = malloc(sizeof(int)*10);
for (int i = 0; i < 10; i++) {
test[i]=i;
}
int **ptr = &test;
printf("%d\n", (*ptr)[1]);
return 0;
}
Please explain to me, why the code works when the array is on the heap, but not on the stack?