2

We know that we can dynamically create variables using pointers as for example:

int *p = new int(5);

We can access its value using * as

cout << *p;

But this is not the case of the array, consider the below code:

int size_array = 5;
int * p = new int[size_array];

if we need to access the value of the first element, we do the following:

cout << p[0];

but why we can't do the same as for a dynamic variable like above?, i.e. using *:

cout << *p[0];
2
  • 1
    You can. *p or p[0]. *(p+1) or p[1]. Et cetera. Commented Dec 4, 2019 at 23:21
  • p[index] is the same as *(p+index), so *p works just fine whether you use new int or new int[size_array], just note that in the second case it only accesses the 1st element in the array, unless p is updated to point at another element. Which you shouldn't do, use a separate pointer for that, if needed. Commented Dec 4, 2019 at 23:27

1 Answer 1

5

p[0] is syntax sugar (for arrays) for:

*(p + 0)

Which is equivalent to:

*p

*p[0] does not work because it is equivalent to:

**p

In other words, de-referencing the pointer/array twice.

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

Comments

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.