🔒 Locked
Basic question about using malloc.
Advertisement
Original Post
Actually, it's:
But yes, it's allowed. Just make sure you allocate enough memory due to the size of the type.
If you used C++, you could do this instead:
Quite a bit cleaner and also type-safe.
int *coords;coords = (int *)malloc(tilesacross*2 * sizeof(int));coords[3]=4;But yes, it's allowed. Just make sure you allocate enough memory due to the size of the type.
If you used C++, you could do this instead:
int *coords;coords = new int[tilesacross*2];coords[3]=4;Quite a bit cleaner and also type-safe.
Your code has errors.
*coords is an int equivalent to coord[0]. malloc returns a void *, an address, which you are then casting into an int. You then seek to access coords[3] and assign it a value - the only meaningful statement in your excerpt.
I think you meant to do this:
*coords is an int equivalent to coord[0]. malloc returns a void *, an address, which you are then casting into an int. You then seek to access coords[3] and assign it a value - the only meaningful statement in your excerpt.
I think you meant to do this:
int * coords;coords = (int *)malloc(tilesacross * 2 * sizeof(int));coords[3] = 4;
I also want to point out that, in C, there is no longer a need to cast malloc. For the low-down, go here: Casting malloc
- xeddiex
- xeddiex
How would he use std::vector in C?
What C++ elements is he using in his code? Also, I don't think many people use malloc in C++. C++ would probably be cleaner in this case, if a little bit slower, but some people prefer C.
Quote:
Original post by Mr Awesome
What C++ elements is he using in his code?
He's casting malloc(), which is actually bad form in C (it makes the code more brittle and can hide an uncommon but hard to find bug) but required in C++.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement