-2

When to use %s instead of %c. For example:

#include <stdio.h>
#include <string.h>
int main(void) {

        char name[31] = "My name is Arnold";

        printf(" %c \n", name);

        return 0;


}

If I change %c to %s I get : My name is Arnold, but if change %s to %c I get something weird like this:

Aamir John
  • 75
  • 2
  • 4
  • 6

1 Answers1

10

Passing wrong arguments to format specifiers is undefined behavior. Therefore you obtain such a weird output.

  1. "%s" expects a pointer to a null-terminated string (char*).

  2. "%c" expects a character (int). Surprised? Read this.

To print the nth character of name, use

printf(" %c \n", name[n]);
Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • 1
    Strictly spealing, `"%c"` expectes `int`. `char` will automatically be extended to `int` for arguments. Quote from [N1256](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf) 7.19.6.1 The fprintf function : "c If no l length modifier is present, the int argument is converted to an unsigned char, and the resulting character is written." – MikeCAT Nov 22 '15 at 15:47
  • @MikeCAT Argh, yes, forgot about that that's different from C++. Thanks. – cadaniluk Nov 22 '15 at 15:48