简体   繁体   中英

How can I initialize a static pointer in C?

I want to use a static pointer in a function in order to point to a number of integers. The number of integers is not yet known while programming but it is known on runtime before the function is used first. So I want to give the function a parameter n and tell it to allocate memory space for n integers to the pointer and keep this. However, I learned that static variables have to initiated in their declaration and this doesn't seem to work here because on the one hand I need the * to declare them as pointers and on the other hand I need the variable name without * to allocate memory. What would a correct declaration and initialisation be for a static pointer? I'm trying to save time or else any computer that I can afford will need years for my program. As I learned that local variables are faster than global variables and pointers sometimes faster than arrays I'm experimenting with that. The function is used billions of times even in smaller test runs so any idea to speed it up is welcome. The use of pointers should also make some functions in the program work together a bit better but if they are local and initialized every time the function is called I don't expect it to be really fast.

Like this:

void foo() {
    static int* numbers = NULL;
    if (numbers == NULL) {
        // Initialize them
    }
}

Be prepared for concurrency issues. Why not make it a global and have a proper init_numbers() and user_numbers() function so that you control when the init happens?

I would try something like this:

void my_proc(int n)
{
    static int* my_static_pointer(0);

    if (my_static_pointer == 0)
    {
        my_static_pointer = malloc(sizeof(int) * n);
    }

    // check the allocation worked and use the pointer as you see fit
}

您可以将指针初始化为null并在以后重用它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM