Click here to Skip to main content
15,895,192 members
Please Sign up or sign in to vote.
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
Comments
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.

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

?
 
Share this answer
 
Comments
Patrice T 3-Nov-23 23:33pm    
+5
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]) 
 
Share this answer
 
Comments
CPallini 3-Nov-23 11:32am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900