【问题标题】:The following code doesn't work .. why?以下代码不起作用..为什么?
【发布时间】:2014-07-16 15:48:40
【问题描述】:

以下代码未按预期工作..

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>

struct dest
{
    char filename[20], keyword[20];
    bool opened;
    FILE * stream;
};


void display_data(const struct dest p) {
    printf("Keyword: %s, Filename: %s, Used: %s\n", p.keyword, p.filename, p.opened ? "Yes" : "No");
}

int main(int argc, char const *argv[])
{
    // float lon, lat;
    // char info[80];

    if ((argc+1) % 2) {
        fprintf(stderr, "Usage: %s file_to_read file_for_unknown type file type file ...\n", argv[0]);
        return 2;
    }

    if (access(argv[1], F_OK) == -1) {
        fprintf(stderr, "File can't be accessed: %s\n", argv[1]);
        return 2;
    }

    const short pairs = (argc-3)/2;
    struct dest data[pairs];

    short times = 4;
    for(short i = 4; i < argc; i += 2) {
        struct dest data[i-times];
        data[i-times].opened = false;
        strcpy(data[i-times].keyword, argv[i-1]);
        strcpy(data[i-times].filename, argv[i]);
        // display_data(data[i-times]);
        times += 1;
    }

    display_data(data[0]);

    return 0;
}

当我尝试运行它时会发生这种情况..

./categorize spooky.csv other.csv UFO UFOS.csv
关键字:?,文件名:�@,已使用:否

这没什么意义..
我一直在努力找出解决方案..静脉..
我不明白问题出在哪里..

参数解析如下:

第一个参数:程序应该读取的文件(暂时忽略)
第二个参数:程序应该存储的文件在 spooky.csv 文件 中找到的任何未知信息(也在此实现中被忽略)
其他参数:它们被成对解析,第一个是关键字,第二个是文件..

我对这个过滤问题的解决方案是创建一个结构数组,并在每个结构中存储关键字、文件名和文件 io 流(我暂时忽略)..

任何帮助将不胜感激..

【问题讨论】:

  • 为什么是if ((argc+1) % 2) 而不是if (argc != NUM_ARGS_EXPECTED)?会更清楚。
  • @FiddlingBits 因为它应该接受尽可能多的参数,只要它们是从第二个参数开始的对..

标签: c arrays string struct io


【解决方案1】:

您有 2 个struct dest data[] 数组。内层掩盖了外层——摆脱它。

如果您打开了警告,您的编译器可能会对此发出警告。

【讨论】:

  • 那么...如何将数组元素声明为结构体?
  • @AmrAyman:FWIW,我已经获取了您的代码,删除了第二个数据声明,编译并在我的系统上运行它(SLES 10 上的gcc -std=c99 -pedantic -Wall -Werror),它产生了预期的输出;我没有遇到分段错误。
  • @JohnBode 谢谢,这是我尝试并提出分段错误的代码:data[0].opened = false; strcpy(数据[0].keyword, argv[4]); strcpy(数据[0].文件名, argv[5]); printf("关键字: %s, 文件名: %s, 使用: %s\n", data[0].keyword, data[0].filename, data[0].opened ? "Yes" : "No") ;
猜你喜欢
  • 1970-01-01
  • 2016-11-12
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 2017-06-15
  • 1970-01-01
相关资源
最近更新 更多