0
$ cat try1.c

#include<stdio.h>
void main()
{
        int arr[]={1,2,3,4};
        printf("%lu--%lu--%lu--%lu\n", arr, arr+1, &arr, &arr+1);
}

$ gcc try1.c -o try1
$ ./try1
140736912750144--140736912750148--140736912750144--140736912750160
$ ./try1
140735606483504--140735606483508--140735606483504--140735606483520
$

&arr gives the base address of the array i.e the 0th element address .. but why does &arr+1 increment with size of array and not by 1 sizeof(int) i.e 4B.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
riteshtch
  • 8,629
  • 4
  • 25
  • 38

2 Answers2

1

In arr + 1, arr is an array decaying to a pointer. A pointer to int. So arr + 1 is the address of arr[1].

In &arr + 1 you take the address of arr which is a pointer to an array of int of length 4. And then you increment that pointer. And because that pointer is a pointer to an array of int of length 4, &arr + 1 is the address just past the end of arr.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • Actually it boils down to the '+' adds sizeof(int) first time and sizeof(int[4]) second time. Precedence is kind of secondary. – david.pfx Jun 26 '14 at 14:20
  • @david.pfx OK. If the precedence was the other way around then `&arr+1` would make no sense at all. I removed that comment. – David Heffernan Jun 26 '14 at 14:30
1

&arr gives the base address of the array i.e the 0th element address

&arr gives you the same address as &arr[0], but it does not mean that pointer type is the same. arr is implicitly converted to int *, where &arr has type int(*)[4]. According to pointer arithmetic + 1 gives you base address +sizeof(int) in first case and +sizeof(int[4]) in the second.

Slava
  • 43,454
  • 1
  • 47
  • 90