gpt4 book ai didi

c - c99 的 ansi c 结构初始化

转载 作者:行者123 更新时间:2023-11-30 15:09:00 25 4
gpt4 key购买 nike

我正在将代码从允许内联变量声明并在结构类型变量初始化中使用数学的 C 版本转换为不允许这两者的版本,并且我需要它们以相同的方式工作。我认为我需要澄清的代码是这样的:

// definitions

typedef struct poly poly_t;

struct poly
{
size_t d; /* degree */
byte c[512]; /* coefficients */
};

// usage in the middle of the method
// (contains non-declaring code before)

poly_t tmp = { 1, {1, gf_exp[i]} };

我将其转换为:

poly_t tmp; // at the beginning of function scope

// then at the same spot of previous declaration

tmp.d = 1;
tmp.c[0] = 1;
tmp.c[1] = gf_exp[i];

这是初始化该结构的正确方法吗?

我需要它们在变量中初始化相同的值。

最佳答案

它们并不相同。从 tmp.c[2]tmp.c[511] 的变量未初始化,并且包含垃圾。

您可以使用 = {0} 强制进行零初始化:

poly_t tmp = {0}; // Set all elements to zero
tmp.d = 1;
tmp.c[0] = 1;
tmp.c[1] = gf_exp[i];

或者,您可以使用初始化程序设置第一个元素:

poly_t tmp = {1}; // Set tmp.d to 1, and other elements to zero
tmp.c[0] = 1;
tmp.c[1] = gf_exp[i];

关于c - c99 的 ansi c 结构初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36936725/

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