+ 1

C - Why no output?

Does *str point to nothing? char *str = "12345"; printf("%s",*str);

13th Sep 2019, 9:27 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
8 Respuestas
+ 5
Yes even I encountered this question in the c challenges. the reason is simple %s cannot be used with a char*. This would help getting the complete string. Printf ("%s",str);
15th Sep 2019, 4:39 AM
Manoj
Manoj - avatar
+ 4
* is used when you want to access single element, printf("%c",*str); // prints 1 printf("%c",*(str+2)); //prints 3
13th Sep 2019, 10:48 AM
Nidhi
+ 3
I'm guessing it's due to the use of %s format specifier - which was meant for string, not a char. *s dereference the <str> and returns the first character in <str> ('1'). Expecting more details from others.
13th Sep 2019, 9:33 AM
Ipang
+ 3
Paolo De Nictolis Because you use the wrong format specifier ,the %s is basically used for the string not for character......
13th Sep 2019, 9:44 AM
Pulkit soni
Pulkit soni - avatar
+ 3
remove * before str, printf("%s",str);
13th Sep 2019, 10:43 AM
Nidhi
+ 2
Adding to what everyone have said, the s format specifier requires the pointer to the initial character as its argument, and then the function will dereference that pointer on its own. You pass *str as its argument, *str has the value of 49 (the character '1'), so the function dereference that value which causes segmentation fault, or no output in SL playground
13th Sep 2019, 10:05 AM
Agent_I
Agent_I - avatar
+ 1
Because it already pointer. Try char *p2 = "54321"; printf ("%s",p2); return 0;
13th Sep 2019, 12:09 PM
Роман Львов
Роман Львов - avatar
+ 1
%s expects char * by writing * before str u are passing char str which in case is 1. If u wanna see string just remove *. If u wanna see output from *str change %s to %c which is for char s
13th Sep 2019, 5:56 PM
David Tsulaia
David Tsulaia - avatar