I saw this question from www.brainbench.com
void *ptr;
myStruct myArray[10];
ptr = myArray;
Which of the following is the correct way to increment the variable
"ptr"?
Choice 1 ptr = ptr + sizeof(ptr);
Choice 2 increment(ptr);
Choice 3 ++(int*)ptr;
Choice 4 ptr = ptr + sizeof(myArray) ;
Choice 5 ptr = ptr + sizeof(myStruct );
THEIR Correct Answer given in this site is: ptr = ptr +
sizeof(myStruct );
But my answer is ++(int*)ptr. The reason is that ptr being void *, we
cannot add any number to it. It must be cast to a valid object before
incrementing.
Which is correct ?
void *ptr;
myStruct myArray[10];
ptr = myArray;
Which of the following is the correct way to increment the variable
"ptr"?
Choice 1 ptr = ptr + sizeof(ptr);
Choice 2 increment(ptr);
Choice 3 ++(int*)ptr;
Choice 4 ptr = ptr + sizeof(myArray) ;
Choice 5 ptr = ptr + sizeof(myStruct );
THEIR Correct Answer given in this site is: ptr = ptr +
sizeof(myStruct );
But my answer is ++(int*)ptr. The reason is that ptr being void *, we
cannot add any number to it. It must be cast to a valid object before
incrementing.
Which is correct ?
Comment