1 registered members (AndrewAMD),
1,454
guests, and 9
spiders. |
Key:
Admin,
Global Mod,
Mod
|
|
|
Using var types in structs?
#178121
01/15/08 22:42
01/15/08 22:42
|
Joined: Mar 2002
Posts: 580 San Francisco
clone45
OP
User
|
OP
User
Joined: Mar 2002
Posts: 580
San Francisco
|
Hello, I'm playing around with structures and lite-c for the first time. I'd like to store a string in my structure. I thought, instead of mess around with char* stuff, maybe I could use a "var" type. Here's my example: Code:
#define new(type) malloc(sizeof(type##)) #define delete(object) free(object)
// Item typedef struct { int id; var name; } Item;
Item* sword = new(Item);
sword->name = "sword"; // This line causes the error
This results in an compile error: "Cannot convert array to fixed."Any ideas? Thanks, - Bret
|
|
|
Re: Using var types in structs?
[Re: Joozey]
#178126
01/16/08 15:10
01/16/08 15:10
|
Joined: Jan 2004
Posts: 2,013 The Netherlands
Excessus
Expert
|
Expert
Joined: Jan 2004
Posts: 2,013
The Netherlands
|
Someone should make a FAQ about memory allocation, stack vs. heap, etc.
You can allocate something in two ways: 1) stack whenever you put "var myvar" or "int myint" or "somestruct mystruct" in a function, you are allocating data on the stack.
2) heap You can allocate a certain number of bytes from the heap with malloc(numbytes). Malloc returns a pointer to the allocated memory (the first byte). You can use it like this: mystruct* p; p = malloc(SIZEOF(mystruct); There are creating functions for all structs in the a7 engine, like string_create(), that use malloc (or C++ new operator).
Deallocation: 1) stack Memory on the stack is deallocated automatically for you when the function ends (actually, when the current scope ends, I think).
2) heap Memory on the heap must be deallocated by you when you don't need it anymore. You can use free() for that. You should use ptr_remove for STRINGs, BMAPs, etc.
So if you want a function that creates a new object (var, float, some struct, whatever), you want that object to still exist after the creating function ends. So you must allocate it on the heap with malloc, and return a pointer to it.
|
|
|
Re: Using var types in structs?
[Re: Excessus]
#178127
01/16/08 18:20
01/16/08 18:20
|
Joined: Oct 2004
Posts: 4,134 Netherlands
Joozey
Expert
|
Expert
Joined: Oct 2004
Posts: 4,134
Netherlands
|
Lol, last week I was stuck on structs that do not exist anymore after a function ends. So it's possible to keep it existing without defining a struct outside the function ... sigh. Thanx alot for the info! Quote:
There are creating functions for all structs in the a7 engine, like string_create(), that use malloc (or C++ new operator).
Is ent_create an exception? For max_entities indicates the maximum amount of entities, and I assumed the compiler made an array with max_entities length. But acknex wouldn't need that if they used allocation right? Or am I being weird now .
Last edited by Joozey; 01/16/08 18:25.
|
|
|
|