Why does the code below compile successfully but fail to write memory other than address 0? (compiled in dev-cpp 6.3)
#include <stdio.h>
#include <stdlib.h>
void alloc_arr(int **d_ptr);
int main() {
int *ptr_i = NULL;
alloc_arr(&ptr_i);
if (ptr_i == NULL) {
printf("ptr_i null");
return 0;
}
printf("ptr_i %x value at 0 %d value at 1 %d",&ptr_i, ptr_i[0], ptr_i[1]);
return 0;
}
void alloc_arr(int **d_ptr) {
*d_ptr = (int *)malloc(2 * sizeof(int));
if (d_ptr == NULL) {
printf("cant allocate memory");
exit(1);
}
*d_ptr[0] = 15;
*d_ptr[1] = 5;
}
I am expecting the code to allocate an array of memory from a function.
You need to revisit operator precedence table.
This is the same as
*(d_ptr[1])=5;whered_ptr[1]is illegal asd_ptronly points to a singleint *.You want
There is also another error in your program:
If you come here, you have already dereference
d_ptrcausing undefined behaviour. Also, according to the text you print, you wantFinally, you print the address of your pointer variable, not where it points to and you also use wrong format specifier:
This should be: