Home > OS >  Why can't I print the integers of an array with using the " * "?
Why can't I print the integers of an array with using the " * "?

Time:09-06

When I create an array and a pointer to that array, why cant I print out the numbers by writing *p[3] instead of just p[3]. When I am doing it with normal numbers like the variable b in the example, I can only access the pointers value by typing the * operator before e (i.e *e). And why isn't it int *p = &array instead of int *p = array?

#include <iostream>

int main(){

    int array[5] = {3, 3, 4, 6, 7};
    int *p = array;
    std::cout << p << "\n" << p[3];

    int b = 5;
    int *e = &b;
    std::cout << "\n" << e << " " << *e;
}   

CodePudding user response:

why cant I print out the numbers by writing *p[3] instead of just p[3]

The expression p[3] is, by definition of the subscript operator [], equivalent to *(p 3), which means that the int element that exists 3 elements after the element pointed to by p is retrieved.

Therefore, *p[3] is equivalent to **(p 3), which does not make sense, because *(p 3) is an object of type int, which cannot be dereferenced. Only pointers can be dereferenced.

And why isn't it int *p = &array instead of int *p = array?

In the declaration int *p = array;, the expression array will decay to a pointer to the first element of the array, i.e. to &array[0]. Therefore, if you wrote int *p = &array; instead, then array would also decay to &array[0], so the entire expression would be equivalent to int *p = &&array[0];, which does not make sense.

CodePudding user response:

operator[] dereferences the pointer. You can also get a pointed to value by writing e[0]. Using both operator[] and the dereferencing asterisk would dereference twice.

  •  Tags:  
  • c
  • Related