Printing data type char with printf()

Viewed 7049

The printf() function uses the format specifier %s to print char *. The standard does not specify how char is implemented as signed or unsigned.

So when char is implemented as signed char, and we use %s to print unsigned char *, is it safe to do this?

Which format specifier should we use in this case?

2 Answers

... when char is implemented in signed char, and we use "%s" to print unsigned char*. Is it safe to do this?

Yes it is safe.

char *cp = ...;
signed char *scp = ...;
unsigned char *ucp = ...;
printf("%s", cp);  // OK.
printf("%s", scp);  // OK.
printf("%s", ucp);  // OK.

(%s) ... the argument shall be a pointer to the initial element of an array of character type. ... C11dr §7.21.6.1 8

The three types char, signed char, and unsigned char are collectively called the character types. C11 §6.2.5 15

If you try this:

#include<stdio.h>

void main()
{
 char name[]="siva";
 printf("name = %p\n", name);
 printf("&name[0] = %p\n", &name[0]);
 printf("name printed as %%s is %s\n",name);
 printf("*name = %c\n",*name);
 printf("name[0] = %c\n", name[0]);
}

Output is:

name = 0xbff5391b  
&name[0] = 0xbff5391b
name printed as %s is siva
*name = s
name[0] = s

So 'name' is actually a pointer to the array of characters in memory.

Related