0

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' });
17
  • printf("%s", "hello"); Commented Nov 10, 2015 at 19:54
  • 1
    Unfortunately they must be in the character array format ('h', 'e', 'l', 'l', 'o'). Commented Nov 10, 2015 at 19:56
  • That's the format it needs to be printed? You need to use a loop in that case Commented Nov 10, 2015 at 19:57
  • printf("%.5s", (char[]){'h', 'e', 'l', 'l', 'o' }); Commented Nov 10, 2015 at 19:57
  • 1
    @Michi he says he wants to print using the syntax {'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. Commented Nov 10, 2015 at 20:26

2 Answers 2

3

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' });
Sign up to request clarification or add additional context in comments.

12 Comments

I believe you can also specify the length in the format string as a variable: printf("%*s", length, array);
that doesn't change the fact that it must either be hard-coded or taken from a second instance of the array (by sizeof()) (which is of course still all done at compile time, but unless both instances are provided by macro expansion then errors can creep in)
Why does it have to be done at compile time? This could be in a function that takes a char* and int. And why do you need another copy for sizeof? char arr[] = { 'a', 'b', 'c' }; int len = sizeof(arr);
It should be %.5s, not %5s
Assumptions -- dangerous things they are.
|
-1

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!

3 Comments

It makes no sense to compare a character to NULL.
@PaulGriffiths: fixed.
this line: while (a[i] != "\0") will not work as expected. Suggest: while (a[i] != '\0') as checking characters, not strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.