5

I know that the declaration of printf is:

int printf ( const char * format, ... );

This means that one can directly print a string instead of using %s and the string as an argument. See the following code:

char str[50];
char *ptr;
//initialize str and ptr

printf(str);  //BAD
printf(ptr);  //BAD
printf("%s",str);  //GOOD
printf("%s",ptr); //GOOD

I've read that printing the string directly as shown in the first two printfs is bad and one should always avoid doing that. Instead, using %s as shown in the last two printfs is better. Both of them prints the two strings correctly.

So, Why is it better to use %s to print a string using printf rather than printing it directly?
What are the problems that arises when one does not use %s to print a string using printf?

Spikatrix
  • 20,225
  • 7
  • 37
  • 83

0 Answers0