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 is
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 use
printf("%c\n", name);
Error i got is
str.c: In function ‘main’:
str.c:9:2: warning: format ‘%c’ expects type ‘int’, but argument 2 has type ‘char *’
%c
is designed for a single character a char, so it print only one element.Passing the char array as a pointer you are passing the address of the first element of the array(that is a single char) and then will be printed :
s
printf("%c\n",*name++);
will print
i
and so on ...
Pointer is not needed for the %s because it can work directly with String of characters.
If you want to display a single character then you can also use name[0]
instead of using pointer.
It will serve your purpose but if you want to display full string using %c
, you can try this:
#include<stdio.h>
void main()
{
char name[]="siva";
int i;
for(i=0;i<4;i++)
{
printf("%c",*(name+i));
}
}
You're confusing the dereference operator * with pointer type annotation *. Basically, in C * means different things in different places:
The thing is that the printf function needs a pointer as parameter. However a char is a variable that you have directly acces. A string is a pointer on the first char of the string, so you don't have to add the * because * is the identifier for the pointer of a variable.
The name of an array is the address of its first element, so name
is a pointer to memory containing the string "siva".
Also you don't need a pointer to display a character; you are just electing to use it directly from the array in this case. You could do this instead:
char c = *name;
printf("%c\n", c);
Source: Stackoverflow.com