Dalam algoritma dan bahasa pemrograman dasar, String atau variable dengan tipe data String atau tipe data untuk mengolah data dari jenis teks atau tulisan, bisa kita gabungkan dengan operasi penggabungan, di dalam algoritma dan juga bahasa pemrograman penggabungan string biasa menggunakan operatur (+), contoh.
I was confused with usage of
%c
and %s
in the following C programOutput is
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
Error i got is
Manuel Selva10.7k1919 gold badges6666 silver badges119119 bronze badges
AspireAspire
31711 gold badge33 silver badges1212 bronze badges
5 Answers
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 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]').
Komal PadiaKomal Padia
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
will print
i
and so on ...
Pointer is not needed for the %s because it can work directly with String of characters.
alerootaleroot56.6k2121 gold badges147147 silver badges192192 bronze badges
You're confusing the dereference operator * with pointer type annotation *.Basically, in C * means different things in different places:
- In a type, * means a pointer. int is an integer type, int* is a pointer to integer type
- As a prefix operator, * means 'dereference'. name is a pointer, *name is the result of dereferencing it (i.e. getting the value that the pointer points to)
- Of course, as an infix operator, * means 'multiply'.
7,64811 gold badge2020 silver badges3232 bronze badges
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:
trojanfoetrojanfoe107k1616 gold badges180180 silver badges216216 bronze badges
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
jwpfox%c
, you can try this:4,1851010 gold badges3737 silver badges4141 bronze badges
ChhaviChhavi