Skip to main content
gamedev.net
🔒 Locked

Basic question about using malloc.

Started by Player_0 Apr 11, 2006 at 11:45 PM 10 replies 1k views
Original Post
Player_0
Player_0
Hello I wanna use malloc to set a block of memory then put numbers into the block so is this allowed?

int *coords;
*coords = (int)malloc(tilesacross*2);
coords[3]=4;

Can I access each position using that method?
Falken42
Falken42
Actually, it's:
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.
Oluseyi
Oluseyi
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:
int * coords;coords = (int *)malloc(tilesacross * 2 * sizeof(int));coords[3] = 4;
Player_0
Player_0
Thank you
xeddiex
xeddiex
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
one..
Mr Awesome
Mr Awesome
How would he use std::vector in C?
BitMaster
BitMaster
It is not clear whether or not the OP wishes to use C or C++ as his code uses elements from both and he does not specify anything.
Mr Awesome
Mr Awesome
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.
jpetrie
jpetrie
Performing the equivalent operations in C++ will be no slower than in C.
Way Walker
Way Walker
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.