我尝试遵循以下link来初始化我的数据:
struct dmparam {
char *p;
char *v;
};
struct dmobj {
int a;
int b;
const struct dmparam * const *dmparam;
};
const struct dmobj dmobj[] = {
{1, 11, NULL},
{2, 22,
(struct dmparam * const []) {//params
{"p1", "v1"},
{"p2", "v2"},
}//params
},
{3, 33, NULL},
};
但是我在汇编中收到警告
test.c:35:3: warning: braces around scalar initializer [enabled by default]
{"p1", "v1"},
^
test.c:35:3: warning: (near initialization for ‘(anonymous)[0]’) [enabled by default]
test.c:35:3: warning: initialization from incompatible pointer type [enabled by default]
test.c:35:3: warning: (near initialization for ‘(anonymous)[0]’) [enabled by default]
test.c:35:3: warning: excess elements in scalar initializer [enabled by default]
test.c:35:3: warning: (near initialization for ‘(anonymous)[0]’) [enabled by default]
test.c:36:3: warning: braces around scalar initializer [enabled by default]
{"p2", "v2"},
^
test.c:36:3: warning: (near initialization for ‘(anonymous)[1]’) [enabled by default]
test.c:36:3: warning: initialization from incompatible pointer type [enabled by default]
test.c:36:3: warning: (near initialization for ‘(anonymous)[1]’) [enabled by default]
test.c:36:3: warning: excess elements in scalar initializer [enabled by default]
test.c:36:3: warning: (near initialization for ‘(anonymous)[1]’) [enabled by default]
test.c:38:2: warning: initialization from incompatible pointer type [enabled by default]
},
^
test.c:38:2: warning: (near initialization for ‘dmobj[1].dmparam’) [enabled by default]
我想念的是什么?
最佳答案
您只是缺少两个索引级别。 dmobj::dmparam
是(在指向 struct dmparam **
的(const)指针的dmparam
的时刻忘记const。
编译器尝试使用dmparam
数组直接初始化,而不是使用指向指针的指针进行初始化。叮当警告是明确的:不兼容的指针类型使用类型为'char [3]'的表达式初始化'struct dmparam * const'。编译器不够聪明,无法猜测您想要什么...
您必须在此处明确:
const struct dmparam params [] = {
{"p1", "v1"},
{"p2", "v2"},
};
const struct dmparam * const p = params;
const struct dmobj dmobj[] = {
{1, 11, NULL},
{2, 22, &p },
{3, 33, NULL},
};
这里的
params
是const dmparam
的数组,p
是指向params
的const指针(另一个变量),然后将p
的地址放在dmobj[1]
中。关于c - 在结构初始化中定义常量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32038121/