Skip to main content
GameDev.net gamedev.net
🔒 Locked

static structure member

Started by gasto Sep 15, 2010 at 4:29 PM 3 replies 650+ views
Original Post
gasto
gasto
How can I define a static(program execution duration) structure member in C?
Intel Core 2 Quad CPU Q6600, 2.4 GHz. 3GB RAM. ATI Radeon HD 3400.
Palidine
Palidine
You don't. C structs are not classes as they are in C++. You can make an entire struct static/global but not just one of its members.

The C way to do it would be:

struct MyStruct{    //my data};int MyStructCommonVar;


Then whatever functions operate on MyStruct do their work on the global MyStructCommonVar as a C++ struct would have done on it's static member.

-me
gasto
gasto

Thanks for the help.
That´s ugly. From a function, I can´t return a string, for example, or any kind of pointer to data, that is member of a structure. It would point to garbage.
Intel Core 2 Quad CPU Q6600, 2.4 GHz. 3GB RAM. ATI Radeon HD 3400.
rip-off
rip-off
In C, instead of returning such a pointer, the idiom is to take a pointer to caller allocated space as a parameter. You then write whatever data into that space. You can return strings by mallocing the appropriate buffer (but the caller must take care to free it), or using the above technique - in which case care must be taken to handle the string length.
Beyond_Repair
Beyond_Repair
Yes, I might add the idiom rip-off mentions is preferable *because* it allows stack allocation (efficient and avoids need of corresponding destroy call in many cases). OTOH it doesn't work for situations where caller doesn't know size of memory required and there isn't any point to try estimating a buffer with a max size.

Either way the code is going to be a lot more verbose than in many other languages.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.