Skip to main content
gamedev.net
🔒 Locked

Pointers to global objects, in C

Started by tekmoto 1 reply 1k views
Original Post
tekmoto
tekmoto
In C, is it OK to have a pointer to a global object? E.g.,: /////////////// Code ////////////// typedef struct _tagAccount { int amt; } Transaction ; Transaction t; Transaction* pTrans; void main() { pTrans = &t }
deathkrush
deathkrush
Yes, it's perfectly fine because the address of t will never change.
deathkrushPS3/Xbox360 Graphics Programmer, Mass Media.Completed Projects: Stuntman Ignition (PS3), Saints Row 2 (PS3), Darksiders(PS3, 360)
Zahlman
Zahlman
Yes.

Alternatively, if you *only* really need(/want) the *pointer* to be global, and just want "a single object... that is accessible through a pointer, for the lifetime of the program", you could set it up to point to a local object in main(). That also allows you to do setup/teardown work in main() and thus gain some control over the order of initialization.

*Do not* try to free() the global object via the global pointer. (Or a local-to-main() object for that matter). Only free() what you malloc() (or calloc()).

Topic Locked

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

Sign in to reply to this topic.