C 编译器错误 - 初始值设定项不是常量
我有一个用于创建新 GQueue
的函数,
GQueue* newGQueue(int n_ele, int ele_size)
{
GQueue* q = (GQueue*) malloc(sizeof(GQueue));
if(!q) return NULL;
q->ptr = malloc(n_ele * ele_size);
if(!(q->ptr))
{
free(q);
return NULL;
}
q->in = q->out = q->count = 0;
q->size = n_ele; q->ele_size = ele_size;
return q;
}
我这样使用它:
volatile GQueue * kbdQueue = newGQueue(10, 1);
但是,以下编译错误发生在这一行:
错误:初始化器元素不是常量
为什么会发生这种情况? 10 和 1 显然是常量,不应该打扰 c99
之前的 C 代码中的 malloc
等。
唯一的标志是-Wall
。
谢谢
I have a function used to create a new GQueue
GQueue* newGQueue(int n_ele, int ele_size)
{
GQueue* q = (GQueue*) malloc(sizeof(GQueue));
if(!q) return NULL;
q->ptr = malloc(n_ele * ele_size);
if(!(q->ptr))
{
free(q);
return NULL;
}
q->in = q->out = q->count = 0;
q->size = n_ele; q->ele_size = ele_size;
return q;
}
I use it like this:
volatile GQueue * kbdQueue = newGQueue(10, 1);
However, the following compilation error occurs at this line:
Error: initializer element not constant
Why does this happen? 10 and 1 are obviously constants which shouldn't bother malloc
, etc in pre c99
C code.
Only flag is -Wall
.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只能在全局变量声明时使用常量值对其进行初始化,而
newGQueue
则不然。这是因为在程序开始执行之前必须初始化所有全局变量。编译器在声明时获取分配给全局变量的任何常量值,并在程序的数据段中使用该值当程序运行时,操作系统加载器将其直接加载到内存中。
只需在声明时将 kbdQueue 初始化为 NULL 并将其初始化为 main 或其他启动函数中的值即可。
You can only initialize global variables at their declaration with a constant value, which
newGQueue
is not.This is because all global variables must be initialized before a program can begin execution. The compiler takes any constant values assigned to globals at their declaration and uses that value in the program's data segment which is loaded directly into memory by the OS loader when the program is run.
Just initialize your kbdQueue at declaration to NULL and initialize it to a value in main or other startup function.
问题不在于 newGQueue 的参数,而是使用 newGQueue 返回值来初始化 kbdQueue。这是可执行代码,在 C 中,所有初始化程序都必须在编译时已知。
这只是 C 语言中的问题; C++ 会毫无问题地接受它。
如果你分解声明和初始化它应该可以正常工作。
The problem is not in the arguments for newGQueue, is for using the newGQueue return value to initialize kbdQueue. That's executable code, and in C all initializers have to be known at compile time.
This is a problem in C only; C++ would accept it without problems.
If you break apart the declaration and initialization it should work OK.