【发布时间】:2013-04-13 06:26:14
【问题描述】:
如果我有点困惑,很抱歉。
我正在尝试使用从输入文件中读取的值填充结构数组。我从文件中读取值没有问题。但是当文件很小并且没有完全填充数组时,剩余的结构中有随机值,我想将这些结构完全设置为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;
}
【问题讨论】:
-
您没有检查 i 是否在您的数组范围内(在这种情况下为 0
-
你不能将结构设置为
NULL;NULL是一个指针值。要么为你的结构定义一些可区分的值来表示缺失数据,要么跟踪你的数组中有多少(或哪些)元素当前有效。
标签: c arrays multidimensional-array struct