4

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?

3
  • 2
    Yes, pointer arithmetic is not limited to starting point at 0. Commented Jan 17, 2022 at 13:50
  • 1
    var is a uint8_t[5]. It can decay to a pointer to first element, but it doesnt always Commented Jan 17, 2022 at 13:56
  • 1
    so var will be pointer No. var is an array. It takes 5*sizeof uint8_t bytes of memory. A pointer only takes sizeof uint8_t * bytes. You can use them in similar ways in most places but they are not the same. Commented Jan 17, 2022 at 14:04

1 Answer 1

3

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 ).

Sign up to request clarification or add additional context in comments.

1 Comment

And, even, a[-1] yields var[1].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.