首页 > 解决方案 > 一种在 C 中知道结构数组中的元素是否为空/NULL 的方法

问题描述

我非常感谢您对这段代码的帮助。

所以我定义了一个结构,然后是一个结构数组:

#define MAX_ITEMS  30
struct item{
    char itemName[30];
    int identification;
    float sale;
};
struct item itemArray[MAX_ITEMS];

然后我有一个函数,它获取数组结构的索引并应该删除该元素,并将没有删除元素的新数组更新到本地.txt文件

printf("item's index please: ");
char input[30];
gets(input);
for (int i=input; i<MAX_ITEMS;i++){ 
    itemArray[i] = itemArray[i + 1];
}

FILE *fp
fp = fopen ("file.txt", "w");
int index = 0;
while(itemArray[index].itemName != ""){
fprintf(fp,"%s\n",itemArray[index].itemName);
fprintf(fp,"%d\n",itemArray[index].identification);
fprintf(fp,"%.2f\n",itemArray[index].sale);
index++;
}
fclose(fp);

所以我期待的是: 在此处输入图像描述

相反,我得到

在此处输入图像描述

在数千行之后完成,如下所示: 在此处输入图像描述

我将不胜感激任何帮助!

标签: arrayscfilestructnull

解决方案


推荐阅读