Reputation: 11
Is there a way I can print an array of characters using 'printf' in the following way (I know this isn't correct C code, I want to know if there is an alternative that will yield the same result).
printf("%s", {'h', 'e', 'l', 'l', 'o' });
Upvotes: 0
Views: 206
Reputation: 1385
How about a simple while loop? Assuming the array is null-terminated, of course. If not - you'll need to adjust to counting the number of characters in the array.
char a[] = {'h','e','l','l','o','\0'};
int i = 0;
while (a[i] != "\0")
{
printf ("%c,", a[i]);
i++;
}
Output:
h,e,l,l,o,
Note: do NOT try this on a char**
! This is for char[]
only!
Upvotes: -1
Reputation: 2792
This will work, but the length of the array must either be hard-coded in the format string or as a parameter or else the array must be defined twice (perhaps by one macro) so that its size can be calculated by the compiler:
printf("%.5s", (char []) {'h', 'e', 'l', 'l', 'o' });
Upvotes: 3