How to initialize a static pointer in C?

I want to use a static pointer in a function to indicate the number of integers. The number of integers is not yet known during programming, but it is known at run time before the function will be used in the first place. So I want to give the function a parameter n and tell it to allocate a memory cell for n integers into a pointer and save it. However, I found out that static variables should be initiated in their declaration, and this does not seem to work here, because, on the one hand, I need * to declare them as pointers, and on the other hand, I need the variable name without * to highlight Memory. What will be the correct declaration and initialization for a static pointer? I am trying to save time, otherwise any computer that I can afford will take years for my program. Since I found outthat local variables are faster than global variables and pointers, sometimes faster than arrays, I'm experimenting with this. The function is used billions of times, even in small tests, so any idea to speed it up is welcome. Using pointers should also improve some functions in the program, but if they are local and initialized every time the function is called, I do not expect it to be very fast.

+3
source share
3 answers

Like this:

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

Get ready for concurrency issues. Why not make it global and have the correct init_numbers () and user_numbers () function so you can control when init happens?

+3
source

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
}
+1
source

You can initialize the pointer to null and reuse it later.

0
source

Source: https://habr.com/ru/post/1730563/


All Articles