Hi,
I have tried following program and the output is 1. Does this mean by default void * can be treated as char *.
Code:#include<stdio.h> int main() { void *ptr; int i; i = sizeof(*ptr); printf("%d",i); return 0; }
Hi,
I have tried following program and the output is 1. Does this mean by default void * can be treated as char *.
Code:#include<stdio.h> int main() { void *ptr; int i; i = sizeof(*ptr); printf("%d",i); return 0; }
Refer to the C standard:
Originally Posted by C99 Clause 6.2.5 Paragraph 19This is unlikely to have changed in C11, so I would conclude that you are observing the effects of undefined behaviour: the compiler could have rightfully refused to compile your program since the type of *ptr is void.Originally Posted by C99 Clause 6.5.3.4 Paragraph 1
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
What platform/compiler are you using?
What can this strange device be?
When I touch it, it gives forth a sound
It's got wires that vibrate and give music
What can this thing be that I found?
If it's undefined behavior than it doesn't matter what the compiler is being used.
Anything that is "Undefined behavior" should never be used in ANY code. Standard C code should be portable to any standards compliant compiler. Undefined behavior is NOT.
As Henny Youngman would say, "Patient: Doctor, Doctor! It hurts when I do this. Doctor: Don't do it!"
What can this strange device be?
When I touch it, it gives forth a sound
It's got wires that vibrate and give music
What can this thing be that I found?
compiler is not even giving warning also regarding sizeof on a incomplete pointer(void *). I am using gcc version 4.6.3. Is there any issue with compiler installation?
Code:#include<stdio.h> int main() { void *ptr; int i; i = sizeof(*ptr); printf("%d",i); return 0; }
It is probably fairer to say it is a concern with quality of implementation of the compiler (i.e. what diagnostics it produces) rather than compiler installation.
sizeof is rather unique in C as it does not evaluate its operand (it only evaluates the size of the result, should the operand be evaluated). You are playing with one edge case which, in practice, few developers would bother to tickle. Such edge cases tend to be fertile ground for finding unexpected or invalid behaviour from compilers.
Last edited by grumpy; 01-23-2015 at 04:03 AM.