Related
I looking to create a variadic function in C that allows to do something like this:
Send({1,2,3,4,5});
Send({4,5,2});
Send({1,1,1,1,1,1,1,1,1,1,1,1,1});
Note there is no length input and the array is placed inline and without any setup or creation of any variable
Currently i am using formal variadic option such as below (example from here), which is quite convenient but also prone to mistakes which are sometimes hard to debug such as forgetting to place the num_args (still compiles), placing the wrong number of elements etc.
int sum(int num_args, ...) {
int val = 0;
va_list ap;
int i;
va_start(ap, num_args);
for(i = 0; i < num_args; i++) {
val += va_arg(ap, int);
}
va_end(ap);
return val;
}
The typical way to define a function that operates on an arbitrary number of arguments of the same type is to use an array:
int sum(const int array[], size_t n)
{
int sum = 0;
while (n--) sum += array[n];
return sum;
}
That would mean that you would have to create an auxiliary array for each call and invoke the function, perhaps with a countof macro that uses sizeof to determine the size of the array and its first member.
As of C99, you can use compound literals to create such arrays:
int s = sum((int[]){1, 1, 2, 3, 5}, 5);
That might be more convenient and typesafe on the array elements, but still has the danger of getting the count wrong.
You can use a variadic macro to combine compound literals and the countof idiom:
#define SUM(...) sum((int[]){__VA_ARGS__}, \
sizeof((int[]){__VA_ARGS__}) / sizeof(int))
(The compound literal argument of the sizeof will only be evaluated for its size.)
Use it like this:
printf("%d\n", SUM(1, 2, 3, 4, 5));
printf("%d\n", SUM(200.0, 30.0, 5.0));
printf("%d\n", SUM());
(I'm not sure whether such a macro is useful, though. The sum example is contrived at best: sum(a, b, c) can be written as a + b + c. Perhaps a min or max macro for more than two arguments might be useful. In general, I find that I have the data I want in array form already when I work in C.)
If you don't want to pass length, you can use a sentinel value to mark the end. If you don't require full range of int, just use (for example) INT_MIN.
Send(1,1,1,1,1,1,1,1,1,1,1,1,1, INT_MIN);
And use that as end condition in your function's loop.
If you need full range of 32 bits, you could pass 64 bit integers so sentinel value can be outside the range of 32 bits. This will be a bit clunky though, you need to make all the parameters be 64 bit then, probably with suffix ll, and this will also make the code less portable/future proof.
One alternative is to use strings. Depending on your purpose, this can be quite robust, because compiler will warn about invalid format string. Here's the code I tested on gcc, and I belive it also works on clang. I hope it is sufficiently self-explanatory with the comments.
The __attribute__ ((format (printf, 1, 2))) part is quite important, it is the only thing making this robust, because it allows the compiler to check the arguments and produce warnings.
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// helper function to get a single string,
// just like vsprintf, except
// returns malloc buffer containing the result text
char *buf_print(const char *fmt, va_list ap) {
int bufsize = 0;
char * buf = NULL;
{
// get the exact size needed for the string,
// ap can only be processed once, a copy is needed
va_list ap2;
va_copy(ap2, ap);
bufsize = vsnprintf(NULL, 0, fmt, ap2);
va_end(ap2);
}
if (bufsize >= 0) {
buf = malloc(bufsize + 1);
if (buf) {
bufsize = vsnprintf(buf, bufsize + 1, fmt, ap);
if (bufsize < 0) {
free(buf);
buf = NULL;
}
}
}
return buf;
}
// get next parseable integer from a string,
// skipping any leading invalid characters,
// and returning pointer for next character, as well as number in *out,
// or returning NULL if nothing could be parsed before end of string
char *parse_next_ll(char *buf, long long *out) {
char *endp = NULL;
while (*buf) {
*out = strtoll(buf, &endp, 10);
if (endp != buf) return endp; // something was parsed successfully
++buf; // nothing was parsed, try again from the next char
};
return NULL; // means *out does not contain valid number
}
// Go through all integers in formatted string, ignoring invalid chars,
// returning -1 on error, otherwise number of valid integers found
int
__attribute__ ((format (printf, 1, 2)))
Send(const char *fmt, ...)
{
int count = -1;
va_list ap;
va_start(ap, fmt);
char * const buf = buf_print(fmt, ap); // needs to be freed, so value must not be lost, so const
va_end(ap);
if (buf) {
count = 0;
long long number = 0;
char *s = buf;
while (s && *s) {
s = parse_next_ll(s, &number);
if (s) {
++count;
printf("Number %d: %lld\n", count, number);
}
}
free(buf);
}
return count;
}
int main()
{
int r = Send("1,2,3,4,%i", 1);
printf("Result: %d\n", r);
return 0;
}
Ouptut of that code:
Number 1: 1
Number 2: 2
Number 3: 3
Number 4: 4
Number 5: 1
Result: 5
I have a function in C, which takes a bunch of arguments, and I would like to treat those arguments like an array and access them by number. For example, say I want to take 6 arguments plus a parameter from 1 to 6, and increment the corresponding argument. I could do:
void myFunc(int arg1,int arg2,int arg3,int arg4,int arg5,int arg6,n)
{
if (n==1) ++arg1;
else if (n==2) ++arg2;
else if (n==3) ++arg3;
else if (n==4) ++arg4;
else if (n==5) ++arg5;
else if (n==6) ++arg6;
}
But that's a bit messy. Is there a neater way to do this?
Although as suggested in the comments passing a pointer to an array may be easier. If you really want to go with arguments then your best bet may be to use a variadric function:
void myFunc(int n, ...)
{
va_list ap;
int arg;
va_start(ap, n);
while (--n)
arg = va_arg(ap, int); /* Increments ap to the next argument. */
va_end(ap);
arg++;
}
I'd do it like this:
void myFunc(int n, ...)
{
va_list args;
va_start(args, n);
int temp;
for(n; n; --n)
{
temp = va_arg(vl, int);
}
temp++;
va_end(args);
}
A few things to note:
This does no handling if n == 0, and will be wrong in that case.
Because C is pass by value, this will increment the variable locally, (as your original function), but the change will NOT take effect outside the function!
You can use a temporary array of pointers to your arguments, then you can access them through this array of pointers:
void myFunc(int arg1,int arg2,int arg3,int arg4,int arg5,int arg6,n)
{
int *array_of_args[] = {&arg1, &arg2, &arg3, &arg4, &arg5, &arg6};
if (n >= 1 && n <= 6)
++*array_of_args[n - 1];
}
This is not better than your original code, but if your code uses the array-access several times, this hack will make the code smaller.
Pass your arguments in as an array. Here I just used literals, but you could replace 1,2,3,4 with your own variables like arg1, arg2, and so on.
int myNumbers[] = { 1, 2, 3, 4 };
myFunc(myNumbers, sizeof myNumbers / sizeof myNumbers[0]);
Then, your function needs to be prepared to accept the array. Also, rather than using six if's to check six arguments, we can write a for loop. However, that is entirely unrelated to the question and I understand you may be doing this for a class assignment.
void myFunc(int *args, int numArgs)
{
int i = 0;
for(i; i < numArgs; i++)
{
if(args[i] == i+1) ++args[i];
}
}
I have a function (see below) that is emitting the following warning:
second parameter of ‘va_start’ not last named argument
What does it means and how to remove it?
The function is as the following:
static int ui_show_warning(GtkWindow *parent, const gchar *fmt, size_t size, ...)
{
GtkWidget *dialog = NULL;
va_list args = NULL;
int count = -1;
char *msg = NULL;
if((msg = malloc(size + 1)) == NULL)
return -12;
va_start(args, fmt);
if((count = snprintf(msg, size, fmt, args)) < 0)
goto outer;
dialog = gtk_message_dialog_new(parent,
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_OK,
"%s", msg);
(void) gtk_dialog_run(GTK_DIALOG(dialog));
gtk_widget_destroy(dialog);
outer: {
if(args != NULL)
va_end(args);
if(msg != NULL)
free(msg);
return count;
}
}
You need to use size instead of fmt:
va_start(args, size);
It is size, not fmt, that is the last parameter that has an explicit name (as opposed to vararg parameters, which have no names). You need to pass the last named parameter to va_start in order for it to figure out the address in memory at which the vararg parameters start.
second parameter of ‘va_start’ not last named argument
What does it means and how to remove it?
Your function has named parameters parent, fmt and size. The C spec says you have to always pass the last named parameter to va_start, for compatibility with older compilers. So you must pass size, not fmt.
(But with a modern compiler, it might work anyway)
I think there is a confusion here: most of people only deal with prinf-like functionsh which have format and varargs. and they think they have to pass parameter name which describes format. however va_start has nothing to do with any kind of printf like format. this is just a function which calculates offset on the stack where unnamed parameters start.
I have the same problem on Ubuntu20.04,Contrary to the answer with the most likes,
the code at the beginning,
void sprintf(char *str, char *fmt, ...) {
va_list list;
int i, len;
va_start(list, 2);
...
}
and then, the code as follows
void sprintf(char *str, char *fmt, ...) {
va_list list;
int i, len;
va_start(list, fmt);
...
}
Problem was sovled.
I wrote a variadic C function which mission is to allocate the needed memory for a buffer, and then sprintf the args given to this function in that buffer. But I'm seeing a strange behavior with it. It works only once. If I have two calls for this function it segfaults.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
char *xsprintf(char * fmt, ...)
{
va_list ap;
char *part;
char *buf;
size_t len = strlen(fmt)+1;
va_start(ap, fmt);
while (part = va_arg(ap, char *))
len += strlen(part);
va_end(ap);
buf = (char*) malloc(sizeof(char)*len);
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
return buf;
}
int main(int argc, const char *argv[])
{
char *b;
b = xsprintf("my favorite fruits are: %s, %s, and %s", "coffee", "C", "oranges");
printf("size de buf is %d\n", strlen(b)); //this works. After it, it segfaults.
/*
free(b);
b = NULL;
*/
b = xsprintf("my favorite fruits are: %s, %s, and %s", "coffee", "C", "oranges");
printf("size de buf is %d\n", strlen(b));
printf("%s", b);
return 0;
}
here's the output of this program:
size de buf is 46
[1] 4305 segmentation fault ./xsprintftest
Am I doing something wrong? Shouldn't I have used va_start multiple times in a single function? Do you have any alternatives? Thanks a lot! :)
You should be using vsnprintf. Use it twice. Once with a NULL destination/zero size to find out the length of the buffer you need to allocate, then a second time to fill the buffer. That way your function will work even if all the arguments are not strings.
As written, it will fail if there are any non-string arguments (%d, %x, %f, etc.). And counting the number of % characters is not a valid way to get the number of arguments. Your result could be too many (if there are literal % characters encoded as %%) or too few (if arguments are also needed for %*s, %.*d, etc. width/precision specifiers).
Pass NULL as the last arg to xsprintf():
b = xsprintf("my favorite fruits are: %s, %s, and %s",
"coffee", "C", "oranges", (void*)0);
Then your while() loop will see the NULL and terminate properly.
As R.. mentions in the comment below and in another answer, the xsprintf function will fail if there are other format arguments. You are better off using vsprintf as explained in the other answer.
My intent here was simply to demonstrate the use of a sentinel with va_arg.
First off, try using vsnprintf. It's just a good idea.
That's not your problem, though. Your problem is that you can't call va_arg more times than there are arguments. It doesn't return the number of arguments. You must either pass in a parameter telling it how many there are, or extract the number of special tokens in the format string to figure out how many there must implicitly be.
That's the reason why printf can choke your program if you pass it too few arguments; it will just keep pulling things off the stack.
The problem is that in the bit of code where you're accessing the va_arg() list without a particular defined end:
va_start(ap, fmt);
while (part = va_arg(ap, char *))
len += strlen(part);
va_end(ap);
The stdargs.h facilities don't have any built-in method for determining when the end of the va_list() occurs - you need to have that explicitly done by a convention you come up with. Either using a sentinel value (as in bstpierre's answer), or by having a count provided. A count can be an explicit parameter that's provided, or it can be implicit (such as by counting the number of format specifiers in the format string like the printf() family does).
Of course, you also have the issue that your code currently only supports the one kind of format-specifier (%s), but I assumed that that's intentional at this point.
Thanks a lot for your answers and ideas! So I rewrote my function like this:
void fatal(const char *msg)/*{{{*/
{
fprintf(stderr, "program: %s", msg);
abort ();
}/*}}}*/
void *xmalloc(size_t size)/*{{{*/
{
register void *value = malloc(size);
if (value == 0)
fatal ("Virtual memory exhausted");
return value;
}/*}}}*/
void *xrealloc(void *ptr, size_t size)/*{{{*/
{
register void *value = realloc(ptr, size);
if (value == 0)
fatal ("Virtual memory exhausted");
return value;
}/*}}}*/
char *xsprintf(const char *fmt, ...)/*{{{*/
{
/* Heavily inspired from http://perfec.to/vsprintf/pasprintf */
va_list args;
char *buf;
size_t bufsize;
char *newbuf;
size_t nextsize;
int outsize;
int FIRSTSIZE = 20;
bufsize = 0;
for (;;) {
if(bufsize == 0){
buf = (char*) xmalloc(FIRSTSIZE);
bufsize = FIRSTSIZE;
}
else{
newbuf = (char *)xrealloc(buf, nextsize);
buf = newbuf;
bufsize = nextsize;
}
va_start(args, fmt);
outsize = vsnprintf(buf, bufsize, fmt, args);
va_end(args);
if (outsize == -1) {
/* Clear indication that output was truncated, but no
* clear indication of how big buffer needs to be, so
* simply double existing buffer size for next time.
*/
nextsize = bufsize * 2;
} else if (outsize == bufsize) {
/* Output was truncated (since at least the \0 could
* not fit), but no indication of how big the buffer
* needs to be, so just double existing buffer size
* for next time.
*/
nextsize = bufsize * 2;
} else if (outsize > bufsize) {
/* Output was truncated, but we were told exactly how
* big the buffer needs to be next time. Add two chars
* to the returned size. One for the \0, and one to
* prevent ambiguity in the next case below.
*/
nextsize = outsize + 2;
} else if (outsize == bufsize - 1) {
/* This is ambiguous. May mean that the output string
* exactly fits, but on some systems the output string
* may have been trucated. We can't tell.
* Just double the buffer size for next time.
*/
nextsize = bufsize * 2;
} else {
/* Output was not truncated */
break;
}
}
return buf;
}/*}}}*/
And it's working like a charm! Thanks a million times :)
Let's say I want to do something like this
void my_printf(char *fmt,...) {
char buf[big enough];
sprintf(buf,fmt,...);
}
What is the proper way of passing the variable number of arguments directly to a function with accepts variable arguments?
sprintf has a va_list form called vsprintf. Pass the va_list you construct locally to it as the last argument.
void my_printf(char *fmt,...) {
va_list ap;
va_start(ap, fmt);
char buf[big enough];
vsprintf(buf,fmt,ap);
va_end(ap);
}
I'm not sure how useful this code will be, as it is C++, but it shows how to check, using a Win32 specific function vsnprintf(), that the buffer allocated is big enough and if not allocates a bigger one. And it returns a std::string, so you would have to use malloc/realloc to handle that. But what the hell:
string Format( const char * fmt, ... ) {
const int BUFSIZE = 1024;
int size = BUFSIZE, rv = -1;
vector <char> buf( size );
do {
va_list valist;
va_start(valist, fmt );
// if vsnprintf() returns < 0, the buffer wasn't big enough
// so increase buffer size and try again
rv = _vsnprintf( &buf[0], size, fmt, valist );
va_end( valist );
size *= 2;
buf.resize( size );
}
while( rv < 0 );
return string( &buf[0] );
}
You can us the vsprintf style functions to get printf style printing for your variable length parameter. However there is no requrement to do so. You can if you choose write your function to keep accepting parameters until it encounters a null pointer.
va_list ap;
char *param;
va_start(ap,fmt);
param = va_arg(ap,char*);
while(param)
{
do something...
param = va_arg(ap,char*);
}
or you can have the number of parameters as the first param to your function
void my_printf(int param_num,...)
{
va_list ap;
char *param;
va_start(ap,fmt);
while(param_num)
{
do something...
param = va_arg(ap,char*);
param_num--;
}
}
Its really up to you, the possibilities are limitless. I think the only real requirement to the ellipses is that it has at least one parameter before the ellipses.