Printing char data type with printf ()

The function printf()uses a format specifier %sfor printing char *. The standard does not indicate how it charis implemented as signed or unsigned.

So, when it charis implemented as a signed one char, and we use it %sfor printing unsigned char *, is it safe to do this?

What format specifier should we use in this case?

+4
source share
2 answers

... when charimplemented 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 must be a pointer to the source element of a character type array .... C11dr ยง7.21.6.1 8

char, signed char unsigned char . C11 ยง6.2.5 15

+6

:

#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]);
}

:

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

, 'name' .

-1

Source: https://habr.com/ru/post/1686417/


All Articles