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' });
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' });
printf("%*s", length, array);char* and int. And why do you need another copy for sizeof? char arr[] = { 'a', 'b', 'c' }; int len = sizeof(arr);%.5s, not %5sHow 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!
NULL.while (a[i] != "\0") will not work as expected. Suggest: while (a[i] != '\0') as checking characters, not strings
printf("%s", "hello");printf("%.5s", (char[]){'h', 'e', 'l', 'l', 'o' });{'h','e','l','l','o'}. There's no'\0'in that. My interpretation of the question is that he does not want to change the array. If you read the question differently that's your prerogative, you can post your own answer or request clarification from OP.