0

I have recently started to learn ANSI C. I have come across this:

int a[7];
*(a+2);

I don't understand how it's possible to add 2 to a. Does it add 2 to every element in a?

Also, what is the function of the *? Does it create a pointer?

Suraj Jain
  • 4,463
  • 28
  • 39
  • http://duramecho.com/ComputerInformation/WhyCPointers.html Take a look at "Pointers used as arrays" section. It's saying get the address where a is, move over 2, then dereference it to get the value. The star (*) can be used to create pointers and to dereference them. They look like the same thing at first but they are different, and it's important to understand which you are looking at in any given case. – jeff carey Feb 05 '17 at 18:24
  • Thank you so much! That tutorial is really useful – user7519940 Feb 06 '17 at 19:12

1 Answers1

2

a+2 causes a to be interpreted as a pointer to a's first element. This is called array decaying.

It then offsets that pointer by 2 and dereferences (*) the resulting pointer. So it's the same as a[2].

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157