以下是引用yu965634383在2017-9-23 09:20:44的发言:
ypedef struct information
{
    char name[32];
    char ID[20];//身份证号码
    char account[32];
    char code[7];//密码
    double money;//8个字节
    struct information *previous , *next;//4个字节
}information , *Information ,a;
我用fwrite 将这个结构体写入文件:fwrite (&a , 99 , 1 , fp);然后用fread (&a , 99 , 1 , fp);读取数据,输出时其它的成员的数据都正确,但是a.money得到的总是一个垃圾值。为什么会这样啊。
内存分配有个叫“字节对齐”问题,通常是用4字节对齐,这时可能要取104个字节才能完整取出这几个数据。
可以这样比较看看:
#include <stdio.h>
main()
{
    struct data
    {
        char name[32];
        char ID[20];//身份证号码
        char account[32];
        char code[7];//密码
        double money;//8个字节
    };
    printf("%d\n", sizeof(struct data));
}
或者:
#include <stdio.h>
#pragma pack (1)
main()
{
    struct data
    {
        char name[32];
        char ID[20];//身份证号码
        char account[32];
        char code[7];//密码
        double money;//8个字节
    };
    printf("%d\n", sizeof(struct data));
}
这样会更好表达些:
#include <stdio.h>
typedef struct data
{
    char name[32];
    char ID[20];//身份证号码
    char account[32];
    char code[7];//密码
    double money;//8个字节
}DATA, *PDATA;
typedef struct information
{
    DATA d;
    struct information *previous , *next;//4个字节
}information, *Information;
int main(void)
{
    information a = {"ABCDEFG","101202303404505606","abcdefg","abc123",123456.789,NULL,NULL};
    FILE *fp = fopen("test.dat", "wb");
    fwrite(&a, sizeof(DATA), 1 , fp);
    fclose(fp);
    DATA b;
    fp = fopen("test.dat", "rb");
    fread(&b, sizeof(DATA), 1 , fp);
    fclose(fp);
    printf("
   name: %s\n", b.name);
    printf("
     ID: %s\n", b.ID);
    printf("account: %s\n", b.account);
    printf("
   code: %s\n", b.code);
    printf("
  money: %lf\n", b.money);
    return 0;
}
[此贴子已经被作者于2017-9-23 16:05编辑过]