【问题标题】:How can I pass 2 values in a function?如何在函数中传递 2 个值?
【发布时间】:2021-05-19 10:34:10
【问题描述】:

现在我正在尝试将名称和 argc 传递给投票函数

但是我得到一堆错误,argc 不起作用,我该如何传递呢?

我有 2 个错误说我的函数调用中有很多参数。

它说它只期望一个参数。

int main(int argc, string argv[]) // I want to pass this argc parameter into my vote function
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    int voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name, argc)) // it doesn't work here
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();

bool vote(string name, int argc) // and here
{
    // TODO
    return false;
}

}

【问题讨论】:

  • 阅读this C reference 关于struct 和指向它们的指针。顺便说一句,标准 C 中不存在 string。阅读 Modern C 并从现有的开源程序(如 GNU bash)中汲取灵感——它主要是用 C 语言编写的。在您的问题中提供一些 minimal reproducible example。使用GCC 编译器作为gcc -Wall -Wextra -g
  • 谢谢,我会看看结构,下次我会尽量少写代码,这样更容易理解
  • 这是 C++ string 还是 CS-50 垃圾课程 string

标签: c function arguments syntax-error


【解决方案1】:

答案在最后一个错误中:

plurality.c:23:6: 之前的声明在这里

布尔投票(字符串名称);

你有一个原型,你必须修复

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 2018-02-06
    • 1970-01-01
    • 2017-07-18
    • 2016-05-16
    • 1970-01-01
    相关资源
    最近更新 更多