sprintf and unsigned int array in C
Solution 1
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.
Solution 2
you can do something like...
char* format_uint_array(char *b, unsigned int* data, int length, char* delim, char* fmt)
{
int i;
char s[50];
b[0] = 0;
for( i = 0; i < length; i++ )
{
s[0]=0;
sprintf( s, fmt, data[i], (i<length-1)?delim : "");
strcat(b, s);
}
return b;
}
then use it like
char buffer[128];
char formattedints[128];
sprintf("(%s)\n", format_uint_array(formattedints, array, 3, ", ", "%d%s"));
Solution 3
No loops:
#include <stdio.h>
int array[3] = {1, 2, 3};
char buffer[128];
char *array_to_str(char * str, int *array, unsigned int n) {
int r;
if (n == 0) return 0;
if (n == 1) r = sprintf(str, "%d", array[0]);
else r = sprintf(str, "%d, ", array[0]);
array_to_str(str + r, array + 1, n - 1);
return str;
}
int main() {
printf("(%s)\n", array_to_str(buffer, array, 3));
return 0;
}
Related videos on Youtube
Chirag
Updated on June 12, 2022Comments
-
Chirag almost 2 years
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 ofarray
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 ofarray
? Something along the lines ofsprintf (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. -
imreal over 11 yearsIs this necessary
s[0]=0;
? -
Chirag over 11 yearsI probably should have been more specific in my question. The format of the string may not necessarily be "(%d, %d, etc)". Although this did give me the idea of using substrings to replace one %d at a time. Thanks!