|
6 registered members (alx, qin, TipmyPip, Quad, 2 invisible),
7,510
guests, and 6
spiders. |
|
Key:
Admin,
Global Mod,
Mod
|
|
|
Re: Dynamically create special entities?
[Re: MrCode]
#178986
01/31/08 23:58
01/31/08 23:58
|
Joined: Jan 2008
Posts: 49 Sweden
Kenchu
Newbie
|
Newbie
Joined: Jan 2008
Posts: 49
Sweden
|
Quote:
Ok, I've come up with this function... Tell me what you think. Is this going to work, or do I have it all wrong?
Code:
MAGNET* mag_create(STRING* filename,VECTOR* pos,int pole) { MAGNET* tmp= malloc(sizeof(MAGNET)); tmp->pole= pole; switch(pole) { case POSITIVE: { ENTITY* ent_post= ent_create("posmagnet.mdl",curpos,phys_objsphere); tmp->entity= ent_post; } case NEGATIVE: { ENTITY* ent_negt= ent_create("negmagnet.mdl",curpos,phys_objsphere); tmp->entity= ent_negt; } } return tmp; }
I looked up malloc() and sizeof() on Wikipedia. I take it what I'm doing when I write "MAGNET* tmp= malloc(sizeof(MAGNET));" is I'm allocating in memory the data size of the MAGNET struct. How do I use this to keep generating more MAGNET*s? doesn't the first MAGNET* get overwritten by the next one that is generated? Or is there more I should know about malloc()?
No, since youre returning a pointer to an area in the memory which youve already allocated. If you wouldve created a local MAGNET object in a function and then returned THAT magnet as a pointer, then things probably wouldve gone real mad after a while (you wouldve returned a pointer to an area which could have anything in it. Local variables are "cleaned" when they reach the end of their block).
When you do:
MAGNET* tmp= malloc(sizeof(MAGNET));
You callocate a memory, and store the adress in tmp. So when you later on return tmp, you arent returning an "objecT", youre returning a pointer to that space you created (usually something like 00FA0E63). It's more or less just a number that you are returning, but since you store that number as a pointer of MAGNET (i.e. MAGNET* my_pointer = mag_create("lolz", vector(0,0,0), 1) for example), lite-c knows that it has the properties of MAGNET struct.
You can try having this in your main:
Code:
function main() { MAGNET* my_pointer = mag_create("lolz", vector(0,0,0), 1); printf("%p", my_pointer); // Prints the location of what the pointer is pointing to. }
Last edited by Kenchu; 02/01/08 00:11.
|
|
|
|