Unexpected output, someone explain. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Unexpected output, someone explain.

The code below explains my confusion with the output. https://code.sololearn.com/cmY4t2acW6Hu/#cpp How can I increment the pointer to move to the next block of the array? Should I only use array element reference syntax "[]" to address the block of the pointer array. So confusing.. An explain would be appreciated. - D3F4U1T

25th Mar 2020, 5:45 AM
D3F4U1T
4 Answers
+ 1
Yes it does. Incrementing the pointer is permanent. As stated, before the second loop, it points to the first element after the original space, and square brackets are really only syntactic sugar for pointer arithmetics behind the scenes. A call like pInt[ 0 ] is implemented as *( pInt + 0 ), so likewise pInt[ i ] <=> *( pInt + i ) is true. The access to an array starts at whereever the pointer points to, and since that is no longer the original first value, you get garbage values. Fixed code is simple: https://code.sololearn.com/c2ot2YsAi7g4/?ref=app
25th Mar 2020, 6:41 AM
Shadow
Shadow - avatar
+ 1
After the allocation, "pInt" points to the first element of the array. By incrementing it, you move it along the elements inside the array to the right, so after the first for-loop, it then points to the memory cell that comes first after your allocated space in memory. Thus accessing those elements will give you garbage values, because it is no longer the space you allocated and initialized earlier. So yes, in this case it would be much simpler to use square brackets to access the elements.
25th Mar 2020, 6:23 AM
Shadow
Shadow - avatar
+ 1
Shadow But that still doesn't explain why did I get garbage values because in second "for" I used square brackets. I need more clarification. Can you post the fixed version of my code.
25th Mar 2020, 6:35 AM
D3F4U1T
+ 1
Thanks Shadow!! I was never expecting pointers to work that way.
25th Mar 2020, 6:53 AM
D3F4U1T