如何初始化在C的malloc静态指针? [英] How to initialize static pointer with malloc in C?
问题描述
我试图启动一个静态变量(函数内)在C的malloc,但我得到了初始不恒定的错误。我知道我不能启动在C非常量静态的,但任何人都可以想到了解决办法?我需要code有,因为这同样的效果:
I'm trying to initiate a static variable (inside a function) with malloc in C, but I'm getting the "initializer not constant error". I know that I can't initiate a static with non constants in C, but can anyone think of a solution? I need the code to have the same effect as this:
static int *p = (int *)malloc(sizeof(int));
有没有窍门/解决方法吗?
Is there a trick/workaround?
编辑:我有一个名为每个标志变为高电平时功能。在这个函数中,我创建并启动一个新的线程。我宣布一个指向一个struct和使用malloc分配内存那么这个指针传递给线程。然后,该函数返回控制。当我重新输入的功能,我刚打开的线程仍在运行,我想能够访问我原本传递给线程的内存区域。这就是为什么我需要一个静态的,这样我可以的malloc在第一次通话,然后在后续调用使用相同的地址。这样我可以从线程信息。所有这一切都避免使用全局变量。
I have a function that is called every time a flag goes high. In this function, I'm creating and starting a new thread. I declare a pointer to a struct and use malloc to allocate memory then pass this pointer to the thread. Then the function returns control. When I re-enter the function, the thread that I opened initially will still be running and I want to be able to access the memory region that I originally passed to the thread. That's why I need a static so that I can malloc on the first call and then use the same address on subsequent calls. This way I can get info from the thread. All this to avoid using global variables.
推荐答案
假设你想要的功能,静态变量:
Assuming you want function-static variables:
int foo(void) {
static int b=1;
static int *p;
if (b) {
p = malloc(sizeof(int));
b = 0;
}
...
}
您可以使用NULL值的p作为检查,只要你的知道的它永远不会是 NULL
第一次通话后。
You can use NULL value for p as a check, as long as you know it will never be NULL
after the first call.
记住要检查在malloc的错误;它是一个的运行时的分配,并且当将不再需要它也应该被释放。
Remember to check for errors in malloc; it is a runtime allocation, and should also be freed when it will not be needed anymore.
这篇关于如何初始化在C的malloc静态指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!