简体   繁体   中英

Passing a Variable Number of Arguments to a C Function

Didnt know how best to describe this but ill explain here. I want to be able to do what i can do with printf IE printf("Variable:%@",astring);

to call the below method i would run write_sock(sock,"my message but i want a variable in here a well");

Does that make sense?

static void write_sock(int sock, const char *msg)
{
    int len = strlen(msg);
    if (write(sock, msg, len) != len)
    {
        perror("short write on socket");
        exit(1);
    }
}

You're talking about the use of variable arguments... (note: vasprintf() may or may not be available... I'm just using it for illustration here)

#include <stdio.h>
#include <stdarg.h>

static void write_sock(int sock, const char *msg, ... )
{
    va_list args;
    va_start( args, msg );
    char* newMsg;

    vasprintf( &newMsg, msg, args );

    int len = strlen(newMsg);
    if (write(sock, newMsg, len) != len)
    {
        perror("short write on socket");
        exit(1);
    }

    free( newMsg );

    va_end( args );
}

Just use sprintf(3) :

char buffer[100];
sprintf(buffer, "Variable: %d", x);
write_sock(sock, buffer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM