user15531308
user15531308

Reputation:

How are *(a + 2) and a[1] related?

We have the variable a, that is the type char*, that stores chars in an array. How are *(a + 2) and a[1] related?

a[1] points to the second element in the array and *(a + 2) points to the second element following the element pointed at to by a. So would the values of these two be the same?

Upvotes: 0

Views: 112

Answers (3)

dbush
dbush

Reputation: 225807

These are not the same.

The syntax E1[E2] is exactly equivalent to *((E1) + (E2)). So *(a + 2) is the same as a[2]. It should now be clear that this is not the same as a[1].

Upvotes: 6

pmg
pmg

Reputation: 108986

Lets say you have char a[] = "bar"; and t goes to address 0xdeadbeec

     | address                  | contents
-----+--------------------------+------------------
high | 0xdeadbeef &a[3]; a+3    | '\0' *(a+3); a[3]
     | 0xdeadbeee &a[2]; a+2    | 'r'  *(a+2); a[2]
     | 0xdeadbeed &a[1]; a+1    | 'a'  *(a+1); a[1]
low  | 0xdeadbeec a; &a[0]; a+0 | 'b'  *(a); a[0]

Note that both though a and &a[0] refer to the same memory address, they have different types. The type of a is char[4], the type of &a[0] is char*.

Upvotes: 0

Costantino Grana
Costantino Grana

Reputation: 3468

a[i] (where a is a pointer and i is an integer type) is exactly *(a + i). So in your example case with char *a;, the expression a[1] is the char at address a + 1. ASCII art schema:

   a[0] a[1] a[2] a[3] a[4]
  +----+----+----+----+----+...
a |    |    |    |    |    |...
  +----+----+----+----+----+...
   a+0  a+1  a+2  a+3  a+4

So, the answer to your question is no. a[2] is just one char after a[1].

Upvotes: 0

Related Questions