gpt4 book ai didi

C-错误 : initializer element is not constant when creating struct *

转载 作者:行者123 更新时间:2023-11-30 18:35:48 30 4
gpt4 key购买 nike

我一直在用 C 编写一个终端应用程序,并且在结构方面遇到了一个奇怪的问题。当我尝试编译时,出现错误“错误:初始化器元素不是常量”。非常感谢任何帮助。

这是我的代码:

typedef struct {
int x;
int y;
char style;
} Pixel;

Pixel *pixels = (Pixel *)malloc(9*128);

最佳答案

问题是您在函数外部调用 malloc。

这将解决您的问题:

typedef struct {
int x;
int y;
char style;
} Pixel;

int main(void) {
Pixel *pixels = malloc(9 * 128);
}

在 C 中,如果变量不在任何函数内部,则不能在变量 init 上调用函数。

int a = 5; //OK
int b = myfunc(); //ERROR, this was your case
int main() {
int c = 5; //OK
int d = myfunc(); //OK
}
<小时/>

从代码检查来看,我假设您认为您的 sizeof(Pixel)9 字节,但情况可能并非如此。当您调用 malloc 时,请使用以下代码:

Pixel *pixels = malloc(sizeof(Pixel) * 128);

此代码将为任何平台上的单行中的 128 Pixel 结构分配内存。

<小时/>

进一步阅读:

Structure padding and packing

Do I cast the result of malloc?

关于C-错误 : initializer element is not constant when creating struct *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44830464/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com