"P.J. Plauger" <pj*@dinkumware .comwrites:
"Ian Collins" <ia******@hotma il.comwrote in message
news:55******** ******@mid.indi vidual.net...
>su************* *@yahoo.com, India wrote:
>>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(myStru ct);
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
incrementin g.
(int*)ptr isn't an lvalue, so you can not increment it.
Nonsense. There are dangers in incrementing (int *)ptr if
myStruct is not on at least as strong a storage boundary as
int (or if you're on a machine where even ten MyStruct are
smaller than a single int). But lvaleness has nothing to do
with it.
Um, are you sure you're not thinking of the C++ rules?
The result of a cast is not an lvalue, and the argument to "++" must
be an lvalue, so Choice 3 is a constraint violation. (Both gcc and
Sun's C compiler complain about it; that doesn't prove anything, but
it does bolster my confidence.) You can add 1 to it, but you can't
increment it with "++".
(Choices 1, 4, and 5 are also constraint violations, since addition
isn't defined for void*. Choice 2 *could* be correct if "increment"
were a carefully crafted macro, but I don't think that's the intent.)
>>Which is correct ?
>ptr = ptr + sizeof(myStruct );
Nonsense. You can't add anything to a void *.
The posed question doesn't answer the burning question,
"increment by what?". One possible sensible interpretation
is to undo the implicit void cast and write:
ptr = ++((myStruct *)ptr);
Yet another is:
ptr = ++((myStruct[10] *)ptr);
These at least have the virtue of being well defined. But
then so does:
ptr = ++(char *)ptr);
so the problem is at least ambiguous. And we still don't
know what the function increment does.
All three of these, if a cast yielded an lvalue, would modify ptr
twice between sequence points and therefore invoke undefined behavior
(<PICKY>and the last one has a missing parenthesis</PICKY>). Changing
"++" to "1 + " should fix that.
I understand that *some* casts in C++ yield lvalues, but I don't know
the rules. Perhaps the question on brainbench.com was actually about
C++? Or maybe it was just wrong.
I'm hesitant to take the risk of disagreeing with P.J. Plauger, but
either I'm right or I'm about to learn something.
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"