简体   繁体   English

如何在C中初始化静态指针?

[英]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. 所以我想给函数一个参数n并告诉它为指针分配n个整数的内存空间并保留它。 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? 为什么不使它成为一个全局的并具有正确的init_numbers()和user_numbers()函数,以便您控制init何时发生?

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并在以后重用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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