-4

EDIT: I'm paraphrasing the original question since it was deemed too broad.

An an array, such as

int x[5] = {1, 2, 3, 4, 5};

What does an expression such as *(x + 2) mean?

Answer: the variable x decays to act as a pointer to the first element of the array, similar to assigning an int pointer to the array name:

int *ptr = x;

Hence, *(x + 2) points to index value 2, and hence has the value 3 in this case.

Original Question:

static int x[8]={10,20,30,40,50,60,70,80};

i) What is the meaning of x?

ii) What is the meaning of (x+2)?

iii) What is the value of *x?

iv) What is the value of (*x+2)?

v) What is the value of *(x + 2)?

Aryaman
  • 109
  • 1
  • 1
    Possible duplicate of [What is array decaying?](https://stackoverflow.com/questions/1461432/what-is-array-decaying) – UnholySheep Jun 20 '18 at 14:08
  • Have a look at "pointer arithmetic". – PhilMasteG Jun 20 '18 at 14:08
  • 2
    The name of an array decays into a pointer to its first element in almost all contexts. `x+2` is, in fact, valid. – Pete Becker Jun 20 '18 at 14:08
  • 1
    You need to read a textbook, SO is not a replacement for that – Slava Jun 20 '18 at 14:09
  • @Slava I did read through the entire pointers chapter in my textbook, as well as (as mentioned in the question) the original textbook from the 90s where the Question was from. It wasn't there. I tried running it on my compiler as well and it threw an error. (in hindsight, since they're valid expressions, this was probably my fault). So I apologise, but asking questions is an integral part of learning and I was trying to do just that. SO usually explains things much better than textbooks and I didn't really see the harm in asking. My bad. – Aryaman Jun 21 '18 at 14:44

1 Answers1

2

x is an array of 8 ints with static storage duration.

The important thing to note that this question is about pointer decay.

When you write (x + 2), x decays to a pointer of type int*, with the address set to the first element of x. So x + 2 is the same as &x[2]; i.e. the address of the third element. This is called pointer arithmetic.

*x is equivalent to x[0]; you are dereferencing x when it's decayed to a pointer. It's value is 10.

*x + 2 is adding 2 to that value 10.

*(x + 2) is the same as x[2], i.e. 30.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483