gpt4 book ai didi

c - 为什么我收到聚集初始化程序不是编译时常量警告?

转载 作者:行者123 更新时间:2023-11-30 14:32:45 25 4
gpt4 key购买 nike

我有这样的结构

struct set
{
char name[SET_NAME_LENGTH + 1];
unsigned int input[INPUT_ARR_SIZE];
};

typedef struct set SETA, SETB, SETC, SETD, SETE, SETF;

然后我有这样的代码

SETA setA;
SETB setB;
SETC setC;
SETD setD;
SETE setE;
SETF setF;

struct set * p_setA = &setA;
struct set * p_setB = &setB;
struct set * p_setC = &setC;
struct set * p_setD = &setD;
struct set * p_setE = &setE;
struct set * p_setF = &setF;

int main()
{
int resultStatus, r;
int num_of_sets = 6;
int i;
int input_method = NOT_CHOOSEN_INPUT;

struct set * struct_arr[] = {
p_setA,
p_setB,
p_setC,
p_setD,
p_setE,
p_setF
};

memcpy(p_setA->name, SETA_NAME, sizeof(SETA_NAME));
memcpy(p_setB->name, SETB_NAME, sizeof(SETB_NAME));
memcpy(p_setC->name, SETC_NAME, sizeof(SETC_NAME));
memcpy(p_setD->name, SETD_NAME, sizeof(SETD_NAME));
memcpy(p_setE->name, SETE_NAME, sizeof(SETE_NAME));
memcpy(p_setF->name, SETF_NAME, sizeof(SETF_NAME));

for(i = 0; i < num_of_sets; i++)
{
printf("\nSET NAME IS : %s\n", struct_arr[i]->name);
}
...
}

但是日志输出不符合我的预期

SET NAME IS : SETA

SET NAME IS : SETA

SET NAME IS : SETA

SET NAME IS : SETA

SET NAME IS : SETA

SET NAME IS : SETA

还有警告

warning: initializer for aggregate is not a compile-time constant

警告

enter image description here

如何解决?

最佳答案

当程序执行时,变量setA会被放置在内存中的某个地方,但编译器不知道在哪里。它的地址,在p_setA中,不是编译时常量,并且不能用作C中的初始化器。只需使用正常赋值而不是初始化。

关于c - 为什么我收到聚集初始化程序不是编译时常量警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59693858/

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