I was confused with usage of %c and %s in the following C program:
#include <stdio.h>
void main()
{
char name[] = "siva";
printf("%s\n", name);
printf("%c\n", *name);
}
Output:
siva
s
Why we need to use pointer to display a character %c, and pointer is not needed for a string
I am getting error when I run
printf("%c\n", name);
I got this error:
str.c: In function ‘main’:
str.c:9:2: warning: format ‘%c’ expects type ‘int’, but argument 2 has type ‘char *’
If you try this:
Output is:
So ‘name’ is actually a pointer to the array of characters in memory. If you try reading the first four bytes at 0xbff5391b, you will see ‘s’, ‘i’, ‘v’ and ‘a’
To print a character you need to pass the value of the character to
printf. The value can be referenced asname[0]or*name(since for an arrayname = &name[0]).To print a string you need to pass a pointer to the string to
printf(in this casenameor&name[0]).