I have this simple code:
#include<stdio.h>
#include<stdlib.h>
int main(){
int (*array)[2] = malloc(sizeof(int)*2);
printf("%p\n",array[0]); //0x13c606700
printf("%p\n",array[0]+1); //0x13c606704
printf("%p", array[1]); //0x13c606708
}
I'm using malloc to allocate memory for an integer array of 2 elements. This returns a pointer for this said array. However, I don't understand why array[0]+1 and array[1] are yielding different addresses. array[0]+1 prints the address at array[0] + 4 which is expected since an integer is of size 4 bytes. But this is not the same for array[1]. Why is this happening? Wouldn't intuition suggest that using malloc on a fixed-size array would enable the programmer to refer to the memory allocated using array notation (i.e array[i])?
int, the declaration should beint *array. You can use what you have for a one-dimensional array, but it's unusual, and your references would need to look like(*array)[i]which isn't what you're doing.int *array(to be allocated) orint array[2]. For the first you needint *array = malloc(sizeof *array * 2);but then the data atarray[0]andarray[1]is indeterminate.