Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings and character with printf

Tags:

c

printf

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 *’ 
like image 251
Aspire Avatar asked Nov 05 '11 10:11

Aspire


People also ask

Can you print a string with printf?

We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.

What does %% mean in printf?

As % has special meaning in printf type functions, to print the literal %, you type %% to prevent it from being interpreted as starting a conversion fmt.


1 Answers

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. If you try reading the first four bytes at 0xbff5391b, you will see 's', 'i', 'v' and 'a'

Location     Data =========   ======  0xbff5391b    0x73  's'  ---> name[0] 0xbff5391c    0x69  'i'  ---> name[1] 0xbff5391d    0x76  'v'  ---> name[2] 0xbff5391e    0x61  'a'  ---> name[3] 0xbff5391f    0x00  '\0' ---> This is the NULL termination of the string 

To print a character you need to pass the value of the character to printf. The value can be referenced as name[0] or *name (since for an array name = &name[0]).

To print a string you need to pass a pointer to the string to printf (in this case 'name' or '&name[0]').

like image 133
Komal Padia Avatar answered Oct 02 '22 15:10

Komal Padia