C 编程 - 结构中的整数值在赋值后变得"random"



我已经搜索了解决此问题的方法,但无法找到解释。我有一个二维结构,里面有一个整数变量。

typedef struct
{
int example;
} Example;
typedef struct
{
Example two_dimensional_array[5][5];
} Example_Outer;

然后,我使用以下函数将所有字段的变量设置为 0 并打印当前值。

void initialise(Example_Outer example)
{
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
example.two_dimensional_array[i][j].example = 0;
}
}
print_example(example);
}

在此打印过程中,所有值都显示为 0,就像它们应该的那样。

输出:

0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 

然后,我运行一个使用完全相同的打印代码的新函数,并收到以下输出:

0, 0, 0, 0, 9, 
0, -394918304, 32551, -2138948520, 32764, 
1, 0, 1, 0, 1775692253, 
21904, -394860128, 32551, 0, 0, 
1775692176, 21904, 1775691312, 21904, -2138948320, 

打印方式:

void print_example(Example_Outer example)
{
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
printf("%d, ", example.two_dimensional_array[i][j].example);
}
printf("n");
}
}

主要方法:

int main( int argc, const char* argv[] )
{   
Example_Outer example;
initialise(example);
printf("---------------n");
print_example(example);
}

为什么变量不保持设置为 0?是什么原因造成的,我该如何解决?谢谢!

首先,你可以用一种简单的方式初始化你的结构,就像下面一样:

Example_Outer example = { 0 };

或者以第二种方式:

typedef struct
{
Example two_dimensional_array[5][5] = { 0 };
} Example_Outer;

现在在你的代码中,你忘记了*在你的void initialise(Example_Outer example)函数中,在这种情况下,你只是在函数中传递一个结构的副本。

所以你应该使用结构的地址作为带有指针(*(的函数的参数:

void initialise(Example_Outer *example)
{
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
example->two_dimensional_array[i][j].example = 0;
}
}
print_example(*example);
}

最后你可以按如下方式传递结构体的地址: (在线测试(:

int main(int argc, const char* argv[])
{
Example_Outer example;
initialise(&example);
printf("---------------n");
print_example(example);
}

最新更新