So, how do I do something like cast a void to an int?
So, how do I do something like cast a void to an int?
Why do you want to cast a void into an int in the first place? If it's a void pointer to an int, that is a serious design flaw as void* pointers are avoided whenever possible.
Maybe he wants to dereference a void pointerOriginally Posted by joeprogrammer
I wanted to use it for a malloced pointer.
Then is there another way to do dynamic memory allocation?Originally Posted by Tonto
You should not need to cast malloc if you are using a modern C compiler. If you are compiling on a C++ setting, you would have to cast malloc, and would be posting on the C++ boards, and then probably using new/new[] anyways. All you would probably have to do with your IDE to compile it as a C program would be to change the extension from .cpp to .c
I'm not compiling with any C++ stuff.
But... I don't think that answered my question. If it did, then I didn't understand it.
> I wanted to use it for a malloced pointer.
As in call malloc, assign to a pointer of the correct type and subscript?
Code:int *p = malloc( 10 * sizeof *p ); for ( i = 0 ; i < 10 ; i++ ) p[i] = 0;
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
He never said anything about casting malloc. I assume they've got something like so:And they want to now know how to use that integer. Thus, the question of 'how do I typecast a void pointer to an int'. The simple answer they were waiting for is:Code:void *foo; foo = malloc( sizeof( int ) );Cast to an integer pointer, since you are in fact using a pointer, then dereference it to make an assignment, or what not.Code:*((int *)foo) = 10;
Quzah.
Hope is the first step on the road to disappointment.
Many thanksOriginally Posted by quzah
Can you please explain this casting step by step?Originally Posted by quzah
Thank you !
"I don't suffer from insanity but enjoy every minute of it" - Edgar Allen Poe
http://www.Bloodware.net - Developing free software for the community.
It casts the void* foo to an int*, and then dereferences it and assigns it to 10.