1

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

2
  • 2
    Your declaration is almost certainly not what you want. You have declared a pointer to an array of two int. This is normally used for a two-dimensional array. If you just want a dynamically allocated array of two int, the declaration should be int *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. Commented Oct 28, 2021 at 14:49
  • An "integer array of 2 elements" is int *array (to be allocated) or int array[2]. For the first you need int *array = malloc(sizeof *array * 2); but then the data at array[0] and array[1] is indeterminate. Commented Oct 28, 2021 at 14:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If I may ask you (and apologise for my lack of knowledge). By using (*array)[2], did I allocate memory for 2 x 1d arrays of sizeof(int)*2 ? Meaning 2 arrays of 8 bytes?
@Nizar No, you only allocated space for two ints, so that's one int[2].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.