Variadic Functions and printf problem with int and char types

Ric Hincapie
2 min readMar 14, 2020
Airport to land ASCII code to printf as string. Source: Istockphoto

I just had hard times trying to solve an apparently simple problem with variadic functions in C programming language, and there was no accurate information wherever I searched. So here is my experience so you can save a lot of time.

I had to write a function with the following prototype that needs to print the strings it is inputed with as argument:

void print_strings (const char * separator, constant unsigned int n, …)

The first argument is how to separate the inputs, the second argument, the number of arguments incoming, and from there on, the strings:

print_strings(“, ”, 3, “Johanna”, “Ricardo”, “Family”)

The goal is that it prints in standard output:

Mama, Ricardo, Family

The problem: printf doesn’t recognize int as chars

error: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’

When you want to input a string as argument to a function, it is converted automatically to its ASCII code, so the word “Family” would look like 70 97 109 105 108 121.

Here’s the code I was working with:

unsigned int counter;va_list my_list;
va_start(my_list, n);for (counter = 0; counter < n; counter++){printf(“%s”, va_arg(my_list(my_list, counter));if (counter != n — 1) printf(“%s”, separator);else printf(“\n”);}va_end(my_list);

The solution for printf an string when argument incoming is ASCII codes

I called this solution “the airport”. I declared a third variable of type pointer to a char (which is technically a string).

char * airport;

and brought my ASCII data type to land on it:

airport = va_arg(my_list, char *);

So, all the way around, my arguments did this: “Family” → 70 97 109 105 108 121 (ASCII code) → “Family”.

Once done this, the printf works beautifully:

printf(“%s”, airport);

Hope this help you guys. Please leave a clap! :)

--

--