So, how do I do something like cast a void to an int?
Printable View
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 pointer :)Quote:
Originally Posted by joeprogrammer
I wanted to use it for a malloced pointer.
Then is there another way to do dynamic memory allocation?Quote:
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;
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.
Many thanksQuote:
Originally Posted by quzah
Can you please explain this casting step by step?Quote:
Originally Posted by quzah
Thank you !
It casts the void* foo to an int*, and then dereferences it and assigns it to 10.