Weird output with varargs in C - c

#include <stdio.h>
#include <stdarg.h>
void f(int parameter, ...)
{
va_list ap;
int j;
va_start(ap, parameter);
for (j = parameter; j >= 0; j = va_arg(ap, int))
printf("%d ", j);
va_end(ap);
printf("\n");
}
int main()
{
f(1, 2, 3, 4);
f(1, 2);
f(1);
}
I write this code, but the output is very strange.Who can tell me the reason.
the output:
esekilvxen245 [10:54am] [/home/elqstux/useful] -> ./a.out
1 2 3 4 1748292352 1748370624
1 2 1748295184 1745597392
1 10 1748295184 1745597392

Your ending condition for the loop is for j to be less than zero, but you don't end the argument list with a negative number in your calls. This means that the loop will continue until it finds a negative number, which can be anywhere on the stack far beyond the arguments you pass.
Call it like e.g.
f(1, 2, 3, 4, -1);

Related

C - Function with Variadic Arguments

I would like to make a function that can take a variable number of parameters at once to do something like this:
void function(char *args[]){ ... } 
int main(){
function("a","b","c");
}
You are looking for Variadic functions.
Check this example:
#include <stdio.h>
#include <stdarg.h>
double average(int num, ...) {
va_list valist;
double sum = 0.0;
int i;
/* initialize valist for num number of arguments */
va_start(valist, num);
/* access all the arguments assigned to valist */
for (i = 0; i < num; i++) {
sum += va_arg(valist, int);
}
/* clean memory reserved for valist */
va_end(valist);
return sum/num;
}
int main(void) {
printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2, 3, 4, 5));
printf("Average of 5, 10, 15 = %f\n", average(3, 5, 10, 15));
}
Output:
Average of 2, 3, 4, 5 = 3.500000
Average of 5, 10, 15 = 10.000000
Read more in Variadic Functions in C and the Reference.
Tip: Think twice before using Variadic functions. As #user694733 commented, they have no compile time type safety or protection against invalid number of arguments. They can usually be avoided with better program design.

I have to reverse the array [1,2,3,4,5,6,7] and i am stuck

#include <stdio.h>
int reverse(int *prr, int i)
{
for (i = 6; i; i--)
{
printf("%d is reverse \n", *prr + i);
}
}
int main()
{
int arrr[] = {1, 2, 3, 4, 5, 6, 7};
int *ptr = arrr;
reverse(ptr, 6);
return 0;
}
The output I am getting is
7 is reverse
6 is reverse
5 is reverse
4 is reverse
3 is reverse
2 is reverse
but not 1!
The loop condition i is equivalent to i != 0 (and for your specific use-case i > 0).
That is, the loop will end when the i reaches 0, so that index will not be printed.
To be able to print the last element, you need to include it in the loop with a condition like i >= 0.
While the off-by-1 question has been answered already, a slightly more idiomatic C way to write it would be to pass the array count as an argument (instead of count-1), and use pointer arithmetic (instead of indexing).
void reverse(int *prr, int i)
{
for (prr += i; i--; )
{ printf("%d is reverse \n", *--prr); }
}
int main()
{
int arrr[] = {1, 2, 3, 4, 5, 6, 7};
reverse(arrr, sizeof(arrr) / sizeof(arrr[0]));
return 0;
}
You have a couple of different ways to write the function. Though as #dxiv pointed out in your comments you want *(prr + i) instead of *prr + i (which by happy mistake just happened to output the same numbers corresponding the elements 1 - 7)
When you want to access a specific element from an array, you options are *(ptr + index) which is equivalent to ptr[index] (or for that matter index[ptr]).
Whenever you need to loop a certain number of times, you can simply decrement the counter, e.g.
#include <stdio.h>
void reverse (int *prr, size_t nelem)
{
while (nelem--)
printf ("%d is reverse\n", *(prr + nelem));
}
int main()
{
int arrr[] = {1, 2, 3, 4, 5, 6, 7};
reverse (arrr, sizeof arrr/sizeof *arrr);
}
Another approach for reversal is a recursive function, e.g.
void reverse (int *prr, size_t nelem)
{
if (nelem) {
printf ("%d is reverse\n", *(prr + nelem - 1));
reverse (prr, nelem - 1);
}
}
or even
void reverse (int *prr, size_t nelem)
{
printf ("%d is reverse\n", *(prr + --nelem));
if (nelem)
reverse (prr, nelem);
}
Example Use/Output
The output of all are equivalent, e.g.:
$ ./bin/reverse_arr_fn
7 is reverse
6 is reverse
5 is reverse
4 is reverse
3 is reverse
2 is reverse
1 is reverse

Why does this variadic C function not print the first argument?

I am trying to make a variadic function in C with stdarg.h, and I followed this tutorial and wrote the code exactly as he did: https://www.youtube.com/watch?v=S-ak715zIIE. I included the output in the code. I cannot figure out why the first argument is not printed, and also, why are there zeros printed at the end? I am beyond confused. Thanks!
#include <stdio.h>
#include <stdarg.h>
void printNums(int num, ...) {
va_list args;
va_start(args, num);
for (int i = 0; i < num; i++) {
int value = va_arg(args, int);
printf("%d: %d\n", i, value);
}
va_end(args);
}
int main() {
printNums(5, 2, 3, 4);
return 0;
}
/*
Output:
0: 2
1: 3
2: 4
3: 0
4: 0
*/
va_start's first argument is the last parameter that isn't variadic. So num holds the 5, and the rest hold the variadics:
#include <stdio.h>
#include <stdarg.h>
void printNums(int num, ...) {
va_list args;
va_start(args, num);
printf("%d: %d\n", 0, num);
for (int i = 1; i <= num; i++) {
int value = va_arg(args, int);
printf("%d: %d\n", i, value);
}
va_end(args);
}
int main() {
printNums(5, 2, 3, 4);
return 0;
}
0: 5
1: 2
2: 3
3: 4
4: 0
5: 0
also, why are there zeros printed at the end? I am beyond confused. Thanks!
Because of this line:
for (int i = 1; i <= num; i++) {
You pass the value 5 as num to printNums(). In the for loop you act as though it describes the number of variadic arguments to read, but it doesn't - you passed 3 variadics, not 5. The last 2 calls to va_start therefore yield undefined behavior, since you've read past the end of valid variadic arguments. It's just mere chance that you happen to get 0 here - it could be some other random value.
Note that there is no way with mere variadic macros to know how many arguments were passed. Nor is there a way to assert their type. You can assume their type and specify their length at runtime if you wish:
$ ./t3
0: 5
1: 2
2: 3
3: 4
#include <stdio.h>
#include <stdarg.h>
void printNums(int num, ...) {
va_list args;
va_start(args, num);
for (int i = 0; i < num; i++) {
int value = va_arg(args, int);
printf("%d: %d\n", i, value);
}
va_end(args);
}
int main() {
printNums(4, 5, 2, 3, 4);
return 0;
}
Variadic functions are primarily valuable when writing functions like printf, where unknown types and quantities of arguments are required (see the example from the man page) Using passing a list of known types would be more conveniently accomplished by passing an array and count int:
$ cat t.c
#include <stdio.h>
void printNums(int count, int* nums) {
for (int i = 0; i < count; i++) {
printf("%d: %d\n", i, nums[i]);
}
}
int main() {
int nums[] = {5,2,3,4};
printNums(4, nums);
return 0;
}
that just doesn't make a very good video about variadics :P

Getting the size of varargs in C?

I am trying to convert some Java code into C. The Java code goes like this:
public static int minimum( int... minimum ) {
assert( minimum.length > 0 );
if ( minimum.length > 0 )
.... // some code that i am able to translate to C without any hassle
}
Now I understand how to have varargs in C by using the stdarg.h header and using the macros provided. However I am stuck doing the minimum.length part.
I have tried strlen but the terminal is giving me an incompatible integer to pointer conversion warning. Is there any way in C where I can replicate the same thing that Java does?
Not directly, as pointed out by #MichaelBurr, you need to pass the number of elements or use a sentinel.
An indirect way to do this is using compound literals:
#include <stdio.h>
#include <stdarg.h>
#include <limits.h>
#define minimum(...) fnminimum(sizeof((int []) {__VA_ARGS__}) / sizeof(int), __VA_ARGS__)
static int fnminimum(int n, ...)
{
int num, min = INT_MAX;
va_list ap;
va_start(ap, n);
while (n--) {
num = va_arg(ap, int);
if (num < min) {
min = num;
}
}
va_end(ap);
return min;
}
int main(void)
{
int a = 1;
printf("%d\n", minimum(2, 30, 7, a++, 4));
return 0;
}
Another (ugly) method using NARGS macros (limited to N args):
#include <stdio.h>
#include <stdarg.h>
#include <limits.h>
#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#define minimum(...) fnminimum(NARGS(__VA_ARGS__), __VA_ARGS__)
static int fnminimum(int n, ...)
{
int num, min = INT_MAX;
va_list ap;
va_start(ap, n);
while (n--) {
num = va_arg(ap, int);
if (num < min) {
min = num;
}
}
va_end(ap);
return min;
}
int main(void)
{
printf("%d\n", minimum(2, 30, 7, 1, 4));
return 0;
}
Output:
1
There is no built-in way to get the number of vararg arguments passed in C.
You need to do one of the following:
pass in a count explicitly,
pass in a count implicitly (as printf() does via the number of conversion specifiers)
or use a sentinel value (such as NULL or 0) to indicate the end of the vararg list
I have seen schemes that use macros and the __VA_ARGS__ identifier to automatically place a sentinel at the end of the varargs list when calling a function.

How to know last argument of va_list?

I'm reading about how to pass optional arguments to function. But I'm unable to understand those. When I see examples, they are confusing and a bit complex. So I just started with a very simple program with what I have understood up to now.
The below program just prints the variables.
void print(int x, ...)
{
va_list ap;
int i = 4; // I know I'm passing only 4 opt variables.
int num;
va_start(ap, x);
while(i--) { // How to know how many variables came in real time?
num = va_arg(ap, int);
printf("%d\n", num);
}
va_end(ap);
return;
}
int main()
{
print(1,2,3,4,5);
return 0;
}
I don't know above program is right or not. But it's working. When I change the i value to 5 printing garbage. How to know how many arguments I got (like argc in main)?
There is no way of knowing how many arguments are passed from inside a variable-argument function, that's why functions such as printf are using special format strings that tells the function how many arguments to expect.
Another way is of course to pass the number of "extra" arguments as the first argument, like
print(4, 1, 2, 3, 4);
Or to have a special value that can't be in the list as last argument, like
print(1, 2, 3, 4, -1);
You also have to take note that the last non-va argument you pass to the function (the argument named num in your case) is not included in the va_list, so in your case with the shown code with 4 as hardcoded number of arguments you will still print garbage, as you pass 1 for the num argument and then three va_list arguments.
Also take care because you use num as both argument and a local variable name.
You can take a look to NARGS macro
Adapted to your code:
#include <stdio.h>
#include <stdarg.h>
#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#define print(...) fnprint(NARGS(__VA_ARGS__), __VA_ARGS__)
void fnprint(int n, ...)
{
va_list ap;
int num;
va_start(ap, n);
while (n--) {
num = va_arg(ap, int);
printf("%d\n", num);
}
va_end(ap);
return;
}
int main(void)
{
print(1, 2, 3, 4, 5);
return 0;
}
EDIT:
If you want to use the same name for macro and function, use () to stop the preprocessor from expanding the function definition:
#define print(...) print(NARGS(__VA_ARGS__), __VA_ARGS__)
void (print)(int n, ...) /* Note () around the function name */
{
...
EDIT 2: Another (ugly) method (but without restriction in the number of args) using compound literals (std 99) and sizeof:
#include <stdio.h>
#include <stdarg.h>
#define print(...) print(sizeof((int []) {__VA_ARGS__}) / sizeof(int), __VA_ARGS__)
void (print)(int n, ...)
{
va_list ap;
int num;
va_start(ap, n);
while (n--) {
num = va_arg(ap, int);
printf("%d\n", num);
}
va_end(ap);
return;
}
int main(void)
{
print(1, 2, 3, 4, 5);
return 0;
}
print is expanded to:
print(sizeof((int []) {1, 2, 3, 4, 5}) / sizeof(int), 1, 2, 3, 4, 5);
But constructions like print(1, 2, 3, a_var++, 4, 5); or print(1, 2, some_func_returning_int(), 4, 5); evaluates a_var++ and some_func_returning_int() two times, thats a big problem.
Another ugly way for both int and strings:
#include <stdio.h>
#include <stdarg.h>
#define print(...) fnprint("{" # __VA_ARGS__ )
fnprint(char *b) {
int count = 0, i;
if (b[1] != '\0') {
for (i =2; b[i]; i++) {
if (b[i] == ',')
count++;
}
count++;
}
printf("\ncount is %i\n", count);
}
int main(void)
{
print();
print("1", "2");
print(1, 2, 3, 4, 5);
return 0;
}

Resources