Click here to Skip to main content
15,904,497 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hy
Why this doesn't work:
C
int main (void) {

	int *x = NULL;

	x = malloc (sizeof(int));

	free(x);

	x = NULL;

	getchar();

	return 0;
}


It says that it cannot convert from 'void *' to 'int *'
Posted
Updated 24-Jun-11 2:48am
v5
Comments
CPallini 24-Jun-11 8:52am    
Because you didn't read any good C programming book?
Albert Holguin 24-Jun-11 11:01am    
lol, that's a good point.. if it was a good book it would explain what it's doing in the example and why...

1 solution

The malloc() function returns a pointer to the allocated memory as a void* which must be cast (by you) to the appropriate type. You need to change your code thus, in order to let the compiler know that you understand what you are doing:
x = (int*)malloc (sizeof(int));


[edit by AH]
The reason malloc() returns a void* is because its a generic call to allocate memory in bytes. Why generic? So it can be used to allocate memory for any type of data (characters, integers, double, structures, anything really).
[/edit]
 
Share this answer
 
v3
Comments
Albert Holguin 23-Jun-11 14:05pm    
its that easy, my 5, added comment (hope you don't mind)
Richard MacCutchan 24-Jun-11 4:06am    
Thanks for the extra comments.
Sergey Alexandrovich Kryukov 23-Jun-11 14:37pm    
Yes, not too hard riddle. My 5. :-)
--SA
Richard MacCutchan 24-Jun-11 4:08am    
It's quite worrying how many developers these days do not seem to have learnt (or been taught) the basics before trying to write more advanced code.
Member 641034 24-Jun-11 7:18am    
Hy
Could You help me with this code that I posted?
Thanks a lot!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900