I am attempting to access elements of an array of integer pointers using solely pointer arithmetic.
#include <stdlib.h>
#include <stdio.h>
#define SIZE 9
int main(int argc, char** argv) {
/* create dynamic array of integers */
int** darr;
darr = malloc(sizeof(int*) * SIZE);
/* print addresses of integer pointers in darr */
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE; j++) {
printf("%p, ", (*(darr + i) + j));
}
printf("\n");
}
/* free dynamic array */
free(darr);
return 0;
}
I understand that the use of malloc is not necessary in this case as I have hard-coded the dimensions of the array into the program, and I am just practicing with such concepts. I am attempting to print out the addresses of the integer pointer in the array, but I can't get the right output. What am I doing wrong?
The output I get from the preceding code is as follows:
0x0, 0x4, 0x8, 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20,
0x0, 0x4, 0x8, 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20,
0x0, 0x4, 0x8, 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20,
0x0, 0x4, 0x8, 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20,
0x0, 0x4, 0x8, 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20,
0x0, 0x4, 0x8, 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20,
0x0, 0x4, 0x8, 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20,
0x0, 0x4, 0x8, 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20,
0x0, 0x4, 0x8, 0xc, 0x10, 0x14, 0x18, 0x1c, 0x20,
malloc()can be necessary even with hard coded values as the stack is of limited size. Any non-trivial sized objects should be allocated dynamically.