Home > Net >  Understanding memory allocation behaviour for arrays using malloc
Understanding memory allocation behaviour for arrays using malloc

Time:10-29

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])?

CodePudding user response:

array[0] is an int[2]. When passed to the function it decays into a pointer to the first element, an int, which is 4 bytes on your system.

array[0] 1 adds the sizeof(int) to the pointer.

array[1] is the next int[2] (out of bounds). That's the sizeof(int) times two.

  • Related