我正在尝试为一些示例部件设置结构数组,然后需要输出到文件。它似乎工作正常,但只会打印前 3 个部分,然后崩溃。
#include "stdio.h"
main()
{
struct stock{
char name[20];
int partNum;
int quantity;
};
struct stock someStock[3];
strcpy(someStock[0].name, "License plate");
someStock[0].partNum = 1234;
someStock[0].quantity= 4;
strcpy(someStock[1].name, "Head lamp");
someStock[1].partNum = 1111;
someStock[1].quantity= 2;
strcpy(someStock[2].name, "Rear wiper");
someStock[2].partNum = 2222;
someStock[2].quantity= 6;
strcpy(someStock[3].name, "Tyres");
someStock[3].partNum = 3333;
someStock[3].quantity= 10;
struct stock *ptr = &someStock[0];
int i;
FILE *file_ptr;
file_ptr = fopen("stock.dat", "w");
for(i=0;i<4;i++)
{
fprintf(file_ptr, "%s %d %d\n",(*ptr).name,(*ptr).partNum, (*ptr).quantity);
ptr++;
}
fclose(file_ptr);
return 0;
}