【问题标题】:C- Setting a array of structs to nullC-将结构数组设置为空
【发布时间】: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


【解决方案1】:

初始化数组:

/* Remaining elements zero-d. */
struct function functionList[10] = { { "", 0 } };

如果空字符串或零表示数组中有未填充的条目,则使用空字符串或零int 终止for

for(j = 0; strlen(functionList[j].name); j++) {

for(j = 0; functionList[j].parameterNumber; j++) {

此外,防止在while 中对functionList 的越界访问:

while(i < 10 && fscanf(fp,
                       "%s %d",
                       functionList[i].name,
                       &functionList[i].parameterNumer) == 2)
{
    i++;
}

请注意,while 之后的 i 的值也会为后续的 for 循环提供终止条件:

for (j = 0; j < i; j++) {

【讨论】:

    【解决方案2】:

    你也可以使用memset:

    memset(functionList, 0, sizeof(functionList));
    

    【讨论】:

      【解决方案3】:

      您可以使用 calloc() 创建数组

      struct function* functionList = calloc(sizeof(struct function), 10);
      

      并更改为引用数组的指针,这样创建的结构体中全为零。

      【讨论】:

      • 但不要强制转换 calloc 的返回值,除非您希望它编译为 C++(只需使用 functionList = calloc(...
      • @JamesMcLaughlin 你是对的,我更新了答案(供未来读者参考,请参阅stackoverflow.com/questions/605845/…
      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多