C语言 为什么结构 int 值没有延续到下一个函数?



我正在练习如何使用二进制文件,并尝试存储,读取和打印一些int值。所以,很自然地,我遇到了一些不影响代码功能的东西(也就是说,到目前为止我希望它做什么),但它让我烦恼,因为我似乎找不到答案为什么会发生它。

我发现,正如您将在下面的代码中看到的那样,如果我在函数"create"中分配"cod.x"作为参数(就像现在一样),然后在"read"函数中将">cod.y">分配给fread但相反,我将其设置为在下一行中打印"cod.x",我最终得到一个 9 的序列。 这是完全有道理的,它是前一个函数中 for 循环分配的最后一个 int 值。

但是,现在,如果在这两个函数中我将"cod.x"换成"cod.y"(也就是说,我命令它打印"cod.y",希望再次看到 9 的序列)我得到 0,就像我会(我认为是正确的,因为它到目前为止尚未使用)与"cod.z"一样。

如果在第二次使用中,我只在功能"创建">中使用了"cod.y",为什么会发生这种情况?9 不应该像之前的"cod.x"那样贯彻到底吗?

我错过了什么?

(有趣的是,如果我在"read"函数中将"cod.z">(而不是"cod.x")分配给 fread ,我发现 9 确实会贯穿始终。然后,在下一行中,我命令它打印"cod.y",9 的序列就好了!

因此,它有点像一个新函数在变量上写入新数据,该变量"先于"前一个函数使用的变量(x声明为"之前">y,y"之前"z...在某种程度上?自动删除后一个变量存储的内容。我不知道这是否是一个相关的观察结果,但我确实指出了这一点。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct nums{
int x, y, z;
}cod;
void create(FILE* BinList);
void read(FILE* BinList);
//void change(FILE* BinList);

int main(void)
{
FILE * BinList;
BinList = fopen("handylist.bin", "wb");
if (!BinList)   return 1;
create(BinList);  //sequence 0123456789 is written in the bin file
BinList = fopen("handylist.bin", "rb");
if (!BinList)   return 1;
read(BinList);  // sequence is printed in both ascending and descending order
return 0;
}

void create(FILE* BinList) {
int i;
for (i = 0; i < 10; i++)
{ 
cod.x = i;      
fwrite(&cod.x, sizeof(struct nums), 1, BinList);  
}
printf("Last stored value: %d", cod.x); 
fclose(BinList);
}

void read(FILE* BinList)
{
int i;
printf("nnCopied Data:");
for (i = 0; i < 10; i++)
{
fread(&cod.y, sizeof(struct nums), 1, BinList);
printf("n%d", cod.y);         //here is where the problem happens
}
printf("nnn");
printf("Values: x:%d, y:%d, z:%dn",cod.x,cod.y,cod.z);  //checking struct values

printf("Order is inverted:n");
for (i = 9; i >= 0; i--)
{
fseek(BinList, sizeof(struct nums) *i, SEEK_SET);
fread(&cod.z, sizeof(struct nums), 1, BinList);
printf("%d n", cod.z);
}
fclose(BinList);
}

至于你对我的提示的回复,我会在这里提供更多细节作为答案。

fwrite(&cod.x, sizeof(struct nums), 1, BinList);  

在这里,您从结构中的x地址写入cod多个字节。你写整个结构。没有问题,因为&cod&cod.x是相同的,因为x是结构的第一个成员。

fread(&cod.y, sizeof(struct nums), 1, BinList);

在这里,您读取了许多字节。你读取整个结构的大小,即你读取一个x,y和z。但是你把它放在cod.y开始。所以你在那里放置了 y、z 和 ??? 的值的字节没有更多的结构来放置字节!因此,您放置"内存中不属于您的"的最后一个字节。

cod.x   y   z    ???
+----+----+----+----....
|    |    |    |
+----+----+----+----....
^    ^    ^
|    |    |
----+----+----+  read puts the data here

最新更新