2

so I was studying about arrays and pointer to an array and I found this code. I was wondering why the last one's address is FE14, isn't it suppose to be the address of the first element plus the (size of data type ) which is 4, so I should be FE04 ?

#include <stdio.h>
int main()
{
    int arr[5];
    printf("%p\n",arr); //----> the output FE00
    printf("%p\n",arr+1); //----> the output FE04
    printf("%p\n",&arr); //----> the output FE00
    printf("%p\n",&arr+1); //----> the output FE14
}
1
  • As a side-note, cast the pointers to type void * prior to printing them using the %p format specifier. Also, arr and &arr[0] are the same thing. Commented Dec 6, 2020 at 19:11

2 Answers 2

3

This is confusing because of the way C arrays can decay into pointer expressions.

With arr and arr+1, the data type of the pointer is int, which on your system is 4 bytes, hence why you see the 4 byte difference between FE00 and FE04.

With &arr and &arr+1, the data type of the pointer is int[5], which is 20 bytes, hence why you see the 20 byte difference between FE00 and FE14

It's a difference of 0x14, which is:

  1 * 16^1 + 4 * 16^0
= 1 * 16   + 4 * 1
= 16       + 4
= 20

If you change the size of your int arr[5] from being 5 ints long to say, 500, you'll see a bigger difference between &arr and &arr+1.

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

1 Comment

thanx for your answer , I didn't knw that &arr will be 20 bytes .
1
printf("%p\n", arr+1);

In this code, arr is an integer pointer, so arr + 1 results in arr + 1 * sizeof(int), which is 4.

printf("%p\n",&arr+1);

In this one, &arr is a pointer to an array of 5 int, so &arr + 1 results in &arr + 1 * sizeof(int[5]), which is 20 (14 in hexadecimal)

Comments

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.