lazba
lazba

Reputation: 149

indexing array in function from the pointer of some element

Imagine some array

uint8_t var[5] = {1,2,3,4,5};

so var will be pointer to the first element of this array, and

uint 8_t* a=var;
b=a[3]

and

b=var[3]

will give the same result.

But will

a = &var[2];
b = a[1];

and

b=var[3];

be same?

Upvotes: 4

Views: 58

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311078

After this assignment

a = &var[2];

that is the same as

a = var + 2;

due to the implicit conversion of the array designator to a pointer to its first element the pointer a points to the element var[2].

So a[0] yields var[2] and a[1] yields var[3].

Pay attention to that the subscript operator a[i] is evaluated like *( a + i ).

So you have a[1] is equivalent to *( a + 1 ) that is in turn equivalent to *( var + 2 + 1 ) that is to *( var + 3 ).

Upvotes: 3

Related Questions