开发者

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 initia开发者_高级运维lisation 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
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜