为什么我在 C 中初始化结构时得到 #28 expression must be a constant value?

Why do I get #28 expression must be a constant value while initializing struct in C?

我正在尝试使用作为函数参数传递的值来初始化 struct,如下所示:

struct my add(uint16_t x, uint16_t y, const char *text, uint8_t b, uint8_t c)
{
    struct my M =
    { x, y, NULL, NULL, text, b, NULL, NULL, c, NULL, NULL};
    array[count] = my;
    count++;

}

然而,在 struct 初始化的线上,我得到:

#28 expression must have a constant value

还有什么方法可以实现它而不出现此错误?

我看到的最重要的问题是您将 text 指针分配给结构的 text 指针,这很可能是错误的,因为 text 字段不是 const.

从参数中删除 const 也可能是错误的,将它添加到 struct 字段可能是好的,如果你确保这个指针指向的内容在整个结构实例的生命周期。

如果你只是memset(&widget, 0, sizeof(widget))1然后像这样初始化每个字段

,你试图做的事情会更清晰
struct widget instance;
memset(&instance, 0, sizeof(instance));

instance.x    = x;
instance.y    = y;
instance.text = malloc(1 + text_size);
if (instance.text != NULL)
    strcpy(instance.text, text);
instance.text_size = text_size;
instance.text_font = text_font;

然后是

widgets[widget_count++] = instance;

部分,不应该进入那个函数,那个函数应该只是

return instance;

无论你在哪里分配了 widgets 数组来操作数组和 widget_count 变量,如果你必须访问它们,不要仅仅为了能够从另一个函数访问它们而将它们设为全局从另一个函数将它们作为参数传递,如果你必须在另一个函数中修改 widget_count,将它的地址作为参数传递。

但是按照你的方式,上下文不明确,所以当代码变得更复杂时,你可能最终会做非常糟糕的事情。


1您需要包含 string.h 才能使用 memset()strcpy()

我会说编译器抱怨你试图用 const 值初始化 struct (char *text) 的非 const 成员 ( const char *text) 作为传入。

要解决此问题,请从参数定义中删除 const 或将 struct 的成员定义为 const.