【问题标题】:How do I determine how many arguments that are being sent to a function? [duplicate]如何确定发送给函数的参数数量? [复制]
【发布时间】:2021-11-12 10:05:15
【问题描述】:

如果我有一个 C 函数,其中一个参数是“...”,我如何确定是否将两个以上的参数传递给该函数?如果发送到my_func() 的第三个参数是int arg2,我该如何访问它?

#include <stdio.h>
int my_func(int arg0, int arg1, ...)
{
    /* How can I determine if 2 or 3 arguemnts are being passed to
     * this function? How do I access the third argument so I could
     * print it out? */
     return 0;
}
int main() {
    my_func(1,2);
    my_func(1,2,3);
    
    return 0;
}

【问题讨论】:

  • 欢迎来到 SO。没有标准的机制。你必须实现你自己的。您可以在固定部分或某些格式字符串中提供参数的数量,或者您可以定义一个特定的值来指示最后一个参数
  • 通常,参数的数量取决于arg0arg1
  • 这能回答你的问题吗? How does Variable length argument works in C?

标签: c arguments variadic-functions c99


【解决方案1】:

在 C 语言中,您无法仅从参数中推断出发送给函数的参数数量。您需要一些支持信息,通常在其中一个参数本身中传递。例如,对于众所周知的printf,第一个参数是一个格式字符串,解析它会告诉函数它应该接受多少其他参数以及它们的类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 2012-11-18
    • 2020-02-21
    • 2012-02-14
    相关资源
    最近更新 更多