非常抱歉如果我有点混乱。
我正在尝试从输入文件中读取值并填充一个结构体数组。我没有任何问题读取文件中的值。但是当文件非常小,无法完全填充数组时,剩余的结构体会有随机值,我希望将这些结构体完全设置为NULL。我试图这样做是因为我想遍历填充好的结构体数组并打印它的值,我需要知道哪些数组值是来自于文件。
以下是我的代码:
struct function {
char name[20];
int parameterNumer;
};
int main(int argc, const char * argv[])
{
struct function functionList[10];
int i =0, j;
int portNumber;
char *configFile = argv[1];
FILE *fp;
fp = fopen(configFile, "r");
if(fp == NULL) {
perror("File not found");
exit(1);
}
fscanf(fp, "%d", &portNumber);
while(fscanf(fp, "%s %d", functionList[i].name, &functionList[i].parameterNumer) == 2) {
i++;
}
functionList[i] = NULL; //getting an error here
for(j = 0; functionList[j] != NULL; j++) { //and here
printf("%s %d", functionList[j].name, &functionList[j].parameterNumer);
}
return 0;
}
NULL
;NULL
是一个指针值。要么为你的结构体定义一些特殊的值来表示缺失的数据,要么跟踪你的数组中当前有效的元素数量(或哪些元素是有效的)。 - Keith Thompson