C global typedef struct 但在函数内进行局部初始化,多次调用函数时不会重置 struct 的值
C global typedef struct but local initialisation within function, values of struct not reset when function is call more than once
我目前正在学习 C 并且遇到以下代码的一些问题:
typedef struct{
string name;
int age;
bool tall;
}
person;
max_index =3;
person x_1[max_index];
int main(void)
{
//lines of code
while (true)
{
function1();
function2();
}
}
int function1(void)
{
person x_2[max_index];
for (int j=0; j< max_index; j++)
{
if (some conditions)
{
x_2[j].name = x_1[j].name;
x_2[j].age = x_1[j].age;
}
}
}
int function2(void)
{
person x_3[max_index];
for (int j=0; j< max_index; j++)
{
if (some conditions)
{
x_3[j].name = x_1[j].name;
x_3[j].age = x_1[j].age;
}
}
}
- 人物结构
- 在评估某些条件时调用 function1 和 function2 的主函数
- function1 和 function2 分别初始化一个新的 person 结构 - x_2 和 x_3
问题:意识到如果主函数调用function1 和function2 > 一次,x_2 和x_3 中的值与上一次调用保持相同。我的理解是,由于 x_2 和 x_3 仅存在于(本地)function1 和 function2 中,因此每次调用这两个函数都会“重置”x_2 和 x_3?即每次调用一个新的 x_2 和 x_3。但事实并非如此......我是 C 的新手,不确定到底是什么问题(无法 google)
更新:的确,printf 有所帮助。代码没有问题,但调试器显示了错误的变量值。
在块范围内声明的变量,例如函数的局部变量,如果未明确初始化,则采用 不确定 值。它们不是“重置”的。这意味着您不能依赖它们具有任何特定的值,并且读取的值甚至可以从一次访问更改为下一次访问。
除此之外,在许多情况下,只需读取一个值不确定的变量就可以在您的程序中触发 undefined behavior。
我目前正在学习 C 并且遇到以下代码的一些问题:
typedef struct{
string name;
int age;
bool tall;
}
person;
max_index =3;
person x_1[max_index];
int main(void)
{
//lines of code
while (true)
{
function1();
function2();
}
}
int function1(void)
{
person x_2[max_index];
for (int j=0; j< max_index; j++)
{
if (some conditions)
{
x_2[j].name = x_1[j].name;
x_2[j].age = x_1[j].age;
}
}
}
int function2(void)
{
person x_3[max_index];
for (int j=0; j< max_index; j++)
{
if (some conditions)
{
x_3[j].name = x_1[j].name;
x_3[j].age = x_1[j].age;
}
}
}
- 人物结构
- 在评估某些条件时调用 function1 和 function2 的主函数
- function1 和 function2 分别初始化一个新的 person 结构 - x_2 和 x_3
问题:意识到如果主函数调用function1 和function2 > 一次,x_2 和x_3 中的值与上一次调用保持相同。我的理解是,由于 x_2 和 x_3 仅存在于(本地)function1 和 function2 中,因此每次调用这两个函数都会“重置”x_2 和 x_3?即每次调用一个新的 x_2 和 x_3。但事实并非如此......我是 C 的新手,不确定到底是什么问题(无法 google)
更新:的确,printf 有所帮助。代码没有问题,但调试器显示了错误的变量值。
在块范围内声明的变量,例如函数的局部变量,如果未明确初始化,则采用 不确定 值。它们不是“重置”的。这意味着您不能依赖它们具有任何特定的值,并且读取的值甚至可以从一次访问更改为下一次访问。
除此之外,在许多情况下,只需读取一个值不确定的变量就可以在您的程序中触发 undefined behavior。