加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 函数原型中的“…”

发布时间:2020-12-16 06:45:29 所属栏目:百科 来源:网络整理
导读:我看到有人的C代码有如下的函数声明: void information_log( const char* fmt,...) 或像块一样 catch(...){} 这是什么意思? 解决方法 省略号…,在函数原型中,用于将函数表示为可变参数.也就是说,它允许将可变数量的参数传递给函数.在这种形式中,函数必须为
我看到有人的C代码有如下的函数声明:

void information_log( const char* fmt,...)

或像块一样

catch(...)
{
}

这是什么意思?

解决方法

省略号…,在函数原型中,用于将函数表示为可变参数.也就是说,它允许将可变数量的参数传递给函数.在这种形式中,函数必须为用户定义一些方式来准确指定它们呈现的参数数量,因为C中的可变参数库函数无法动态地确定此信息.

例如,stdio函数printf是原型的一个这样的函数:

int printf(const char *format,...);

据推测,根据两个原型之间的相似之处,您描述的information_log函数旨在反映printf的大部分功能,甚至可能在内部使用printf或其中一个表兄弟.

以下是如何实现可变参数函数的示例:

// cstdarg provides access to the arguments passed to the ellipsis
#include <cstdarg> // or (#include <stdarg.h>)
#include <cstdio>
#include <cstring>

// Concatenates as many strings as are present
void concatenate(char ** out,int num_str,...)
{
    // Store where the arguments are in memory
    va_list args;

    // Find the first variadic argument,relative to the last named argument
    va_start(args,num_str);

    int out_len = 0;
    int * lengths = new int[num_str];
    char ** strings = new char*[num_str];

    // Extract the strings from the variadic argument list
    for(int i = 0; i < num_str; i++)
    {
        // Specify the position in the argument list and the type
        // Note: You must know the type,stdarg can't detect it for you
        strings[i] = va_arg(args,char *);
        lengths[i] = strlen(strings[i]);
        out_len += lengths[i];
    }

    // Concatenate the strings
    int dest_cursor = 0;
    (*out) = new char[out_len + 1];
    for(int i = 0; i < num_str; i++)
    {
        strncpy( (*out) + dest_cursor,strings[i],lengths[i]);
        dest_cursor += lengths[i];
    }
    (*out)[dest_cursor] = '';

    // Clean up
    delete [] strings;
    delete [] lengths;
    va_end(args);
}

int main()
{
    char * output = NULL;

    // Call our function and print the result
    concatenate(&output,5,"The ","quick"," brown ","fox ","jumps!n");
    printf("%s",output);

    delete [] output;
    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读