Sign in to follow this  
tekmoto

Pointers to global objects, in C

Recommended Posts

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; }

Share this post


Link to post
Share on other sites
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()).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this