sprintf and unsigned int array in C

c, printf, variadic-functions

Solution

Passing all elements in a single `va_list` is not going to help, because the format string needs to be created in a loop anyway. Since you cannot escape the loop anyway, you might as well do the printing in the same loop:

int data[] = {12, 345, 6789, 101112};
char buf[128], *pos = buf;
for (int i = 0 ; i != 4 ; i++) {
    if (i) {
        pos += sprintf(pos, ", ");
    }
    pos += sprintf(pos, "%d", data[i]);
}
printf("%s\n", buf);

Here is a link to a demo on ideone.

Problem

I have a pointer to an array of ints and the length of the array as such: ``` unsigned int length = 3; int *array; // Assume the array has 3 initialized elements ``` I also have a string and a buffer (assume it is sufficiently large) to put into sprintf as such: ``` char buffer[128]; const char *pattern = "(%d, %d, %d)\n"; ``` Assume that `pattern` will only have "%d"s and other characters in it, but could be any form (i.e. "Test %d: %d" or "%d %d"), and that the length of `array` will always be the same as the number of "%d"s. Since the length of the array can be anything, is there any way that I can do `sprintf (buffer, pattern, &array[0], &array[1], &array[2])` without explicitly enumerating the elements of `array`? Something along the lines of `sprintf (buffer, pattern, array)`. I can write as many helper functions as are necessary. I was thinking of faking a va_list, but this seems to be bad practice as it restricts the program to a certain compiler.

Original source