I know a pointer is usually assigned upon its declaration, but I wondering if there's any way to create a global pointer in C. For example my code below: is it a good practice?
static int *number_args = NULL;
void pro_init(int number)
{
number_args = &number; /* initialize the pointer value -- is this okay? */
}
If you feel the need (why?) to have a global pointer then initialise if off the heap.
That is valid. There are many good reasons to have global variables, especially static global variables. But if something doesn't need to be global, it's better to not make it global.
Also keep in mind that if more than one thread accesses that variable, you'll need to protect it somehow, probably with a mutex, or you may have race conditions.
Also, keep in mind that "number" is a stack variable. Arguments to functions and local variables are both allocated on the stack, and cease to exist outside of their scope. So unless "pro_init()" either never returns, or sets the variable back to NULL before it returns, you'll end up with an invalid pointer.
You might use heap memory instead, for example:
number_args = malloc(sizeof(int));
if (number_args == NULL) { /* handle malloc error */ }
*number_args = number;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With