15,999,253 members
1.00/5 (1 vote)
See more:
C++
```int ray[5] = { 2, 4, 6, 8, 10 };
int* p = ray;
*p = ray[2];
std:: cout <<  *p <<" "<< *(p + 1) << std::endl;```

What I have tried:

I need an explanation of why it printed 6 4 instead of 6 8.
Posted
Updated 4-Nov-23 1:55am
v2
jeron1 3-Nov-23 10:35am
p starts out is a pointer to array (ray) index 0. You then set the contents of the memory that the pointer points to, to the contents of ray[2] which is 6. Your pointer p is still pointing to array index 0 at this point. You print the contents pointed to by p (array index 0) which is now 6, you increment p so it points to array index 1, which contains the value of 4.

## Solution 1

C++
```int ray[5] = { 2, 4, 6, 8, 10 };
int* p = ray;  // p points to ray[0]
*p = ray[2];   // assign the value of ray[2] (6) to what p points to (ray[0])
// ray now is { 6, 4, 6, 8 10 }
// p still points to ray[0];
std::cout << *p << *(p+1) << std::endl;  // prints 6 (ray[0], *p) and 4 (ray[1]) ```

CPallini 3-Nov-23 11:32am
5.

## Solution 2

Did you possibly mean
C++
```int ray[5] = { 2, 4, 6, 8, 10 };
int* p = &ray[2];
std:: cout <<  *p <<" "<< *(p + 1) << std::endl;
```

?