简体   繁体   English

需要动态分配(初始化)的静态变量

[英]Need dynamically allocated (initialized) static variable

I need a static string(equivalent) variable in C and I'm having troubles implementing something like that. 我在C中需要一个静态字符串(等效)变量,而在实现类似功能时遇到了麻烦。

I need to add content to that string every time the function is called. 每次调用该函数时,我都需要向该字符串添加内容。 I tried with 我尝试过

static char *result = (char*)calloc(0, sizeof(char));

But that way I got: 但是这样我得到了:

error: initializer element is not constant 错误:初始化元素不是恒定的

Which makes sense, but I really don't know how to do this differently (tried with global variable also, but no success). 这样做是有道理的,但是我真的不知道该怎么做(也尝试使用全局变量,但没有成功)。

Anyone can help? 有人可以帮忙吗?

static initializers must be constant, as your error message indicates. 如错误消息所示,静态初始值设定项必须为常数。

Assign it NULL , then in some other function, test if it's NULL, allocate the resources it needs (some sensible default) and go from there. 将其分配为NULL ,然后在其他函数中测试其是否为NULL,分配所需的资源(一些合理的默认值),然后从那里去。 Ensure you do clean up after you're done, and if this is a threaded environment, I suggest you go a different route put this in other storage that you pass along wherever you need it. 确保完成后进行清理,如果这是线程环境,我建议您采用其他方法将其放置在其他存储中,以备不时之需。

If you need to increase array length, use realloc instead. 如果需要增加数组长度,请改用realloc。


char *buf = NULL;

while(/* some loop here */){
    buf = realloc(buf, sizeof(/* new content */));
    ... // copy your new content to buf here
}

If you only add content, maybe better to use lists instead? 如果仅添加内容,则最好使用列表呢?

I was able to get this to work for a "fixed" size array, ie the length can be defined during run-time, NOT compile time. 我能够使它适用于“固定”大小的数组,即长度可以在运行时而不是编译时定义。 I created a function which has the empty pointer itself A as an input, then alters it within and also returns it. 我创建了一个函数,该函数将空指针本身A作为输入,然后在其中进行更改并返回它。 The length len is custom run-time length: 长度len是自定义运行时长度:

char *malloc_char_array(char* &A, int len);

Then call that function in the array initialization: 然后在数组初始化中调用该函数:

static char *result = malloc_char_array(result, 50); //test length of 50

The static initialization only occurs the very first time the function is called, so it works great for arrays that need to be dynamic in size (ie not defined during compile time), yet still remain fixed throughout the entire run of the program. 静态初始化仅在函数第一次被调用时发生,因此它对于需要动态大小(即在编译时未定义)但仍在程序整个运行期间保持固定的数组非常有用。

And the allocating function would look something like: 分配函数如下所示:

char *malloc_char_array(char* &A, int len)
{
    A = (char*) malloc(len * sizeof(char));
    return A;
}

With this method there's no need to free the "static" allocated memory, just let it stay in the stack until the program quits. 使用这种方法,无需释放“静态”分配的内存,只需将其保留在堆栈中,直到程序退出即可。

The most common way I've seen of doing this is to initialize a pointer to NULL, and store a length- optionally an end pointer is stored as well. 我见过的最常见的方法是初始化一个指向NULL的指针,并存储一个长度,也可以选择存储一个结束指针。 When the function is called, check to see if you have enough space in your buffer available, and if not then realloc the memory chunk. 调用该函数时,请检查缓冲区中是否有足够的可用空间,如果没有,请重新分配内存块。 Usually you don't want to realloc every time, and instead grow by either some fixed amount (usually selected based on the memory alignment of the system), or else to double the previous size (be sure to make sure you actually have enough free space!). 通常,您不想每次都重新分配,而是以某个固定量增长(通常根据系统的内存对齐来选择),或者将以前的大小增加一倍(请确保您实际上有足够的空闲空间)空间!)。

#define MYDATA_GROW_AMOUNT (12345) //exploit memory alignment on your system
...
/* if the compiler supports it, consider using __thread__ here */
static /* __thread__ */ char  *mydata     = NULL;
static /* __thread__ */ char  *mydata_end = NULL;
static /* __thread__ */ size_t mydata_len = 0;
...
/* gcc? you might want to use
       if(__builtin_expect((mydata_len < required_data_len),0))
   here instead */
if(mydata_len < required_data_len)
{
    mydata_end = mydata + mydata_len;
    mydata_len += MYDATA_GROW_AMOUNT;
    mydata = realloc(mydata,mydata_len);
}
...

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

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