我创建了一个结构:
typedef struct aeroplane
{
int seat;
char rsv[10];
char fName[20];
char lName[20];
} AERO;
并在主函数中创建一个数组,然后对其进行初始化:
#define ROWS 3
#define COLS 4
AERO arr[ROWS][COLS] =
{
{
{0, "Empty", "NULL", "NULL"},
{0, "Empty", "NULL", "NULL"},
{0, "Empty", "NULL", "NULL"},
{0, "Empty", "NULL", "NULL"}
},
{
{0, "Empty", "NULL", "NULL"},
{0, "Empty", "NULL", "NULL"},
{0, "Empty", "NULL", "NULL"},
{0, "Empty", "NULL", "NULL"}
},
{
{0, "Empty", "NULL", "NULL"},
{0, "Empty", "NULL", "NULL"},
{0, "Empty", "NULL", "NULL"},
{0, "Empty", "NULL", "NULL"}
}
};
我使用此函数将数组保存到test.dat
:
void save(AERO * arr, FILE * fp)
{
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
fprintf(fp, "%d %s %s %s\n",
((arr + i) + j) -> seat, ((arr + i) + j) -> rsv, ((arr + i) + j) -> fName, ((arr + i) + j) -> lName);
}
fprintf(fp, "\n");
}
}
这是test.dat
显示的内容:
0 Empty NULL NULL
0 Empty NULL NULL
0 Empty NULL NULL
0 Empty NULL NULL
0 Empty NULL NULL
0 Empty NULL NULL
0 Empty NULL NULL
0 Empty NULL NULL
0 Empty NULL NULL
0 Empty NULL NULL
0 Empty NULL NULL
0 Empty NULL NULL
看起来像我的意图。
但是,当我使用此函数检索数据时:
void read(AERO * arr, FILE * fp)
{
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
fscanf(fp, "%d %s %s %s",
&((arr + i) + j) -> seat, ((arr + i) + j) -> rsv, ((arr + i) + j) -> fName, ((arr + i) + j) -> lName);
}
}
}
然后将其打印出来:
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
printf("dummy[%d][%d]\nseat = %d\nrsv = %s\nfName = %s\nlName = %s\n\n",
i, j, dummy[i][j].seat, dummy[i][j].rsv, dummy[i][j].fName, dummy[i][j].lName);
}
}
输出不是我想要的:
dummy[0][0]
seat = 0
rsv = Empty
fName = NULL
lName = NULL
dummy[0][1]
seat = 0
rsv = Empty
fName = NULL
lName = NULL
dummy[0][2]
seat = 0
rsv = Empty
fName = NULL
lName = NULL
dummy[0][3]
seat = 0
rsv = Empty
fName = NULL
lName = NULL
dummy[1][0]
seat = 0
rsv = Empty
fName = NULL
lName = NULL
dummy[1][1]
seat = 0
rsv = Empty
fName = NULL
lName = NULL
dummy[1][2]
seat = 0
rsv =
fName =
lName = ▒▒
dummy[1][3]
seat = -2144188312
rsv =
fName =
lName =
dummy[2][0]
seat = 0
rsv =
fName =
lName =
dummy[2][1]
seat = 970037024
rsv = ▒
fName =
lName = ▒
dummy[2][2]
seat = -14080
rsv =
fName =
lName =
dummy[2][3]
seat = 31
rsv =
fName =
lName =
我希望输出已经定义了3行4列。但是它不仅返回较小的值,而且还返回损坏的值。我错过了什么吗?
答案 0 :(得分:0)
AERO[ROWS][COLS]
与AERO*
不兼容。打开编译器警告,并注意警告。
– pmg