+ 6

C - Printing a char*

Why does this result in a segmentation fault? And why, if I use %d instead of %s, I get a useless 49? char *str = "12345"; printf("%s", *str);

10th Feb 2020, 6:23 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
12 Réponses
+ 10
*str point to the first charecter of "12345". So str[0]='1', when %d is used to display then it is converted to intiger or ascii value 49. But with accessing %s, the str is pointer of char*, the location of string in memory, cannot be converted to string type.. Since it point to single value but accessing more than that causes segmentation error... Edit: %s takes that *str value as address for retrieving string.. So cause segment error.. For some more clarity, see ~ swim ~answer below..
10th Feb 2020, 6:57 PM
Jayakrishna 🇮🇳
+ 6
You get 49 because it only reads 1 (as char) and the ascii of '1' is 49. If you change that 1 to 0 for example, when you print %d it will print out 48 as the ascii of '0' (Character 0, not integer 0). For %s, it gives you segmentation fault because of the parameter, when you put *str it means str[0] at the first. Pointer is "pointing", try to change it to %c to see what I mean, and if you want to print it as string, use str instead of *str. Oh and also try these, printf ("%d", *str); printf ("%d", *str+1); printf ("%d", *str+2); You can try to change %d to %c to understand better my explanation because I'm kinda bad to explain something when its not face to face.
11th Feb 2020, 4:49 AM
LastSecond959
LastSecond959 - avatar
+ 4
*str which is '1' has an ASCII value of 49 in decimal. So, %d prints 49. If you use %s it will try to print a null terminated string of chars starting at memory address 49 (in decimal). This address is most likely not accessible, causing the segmentation fault.
11th Feb 2020, 10:42 PM
Sonic
Sonic - avatar
10th Feb 2020, 6:39 PM
Salman Nazeer
Salman Nazeer - avatar
+ 3
~ swim ~ Yes. Illigal, unavailable access.. My meaning the same.. Is there need any changes? I think, It should be "incompatible" , instead of "cannot be converted"...! Right?
10th Feb 2020, 7:23 PM
Jayakrishna 🇮🇳
+ 3
~ swim ~ Thanks for letting me know that..
10th Feb 2020, 7:37 PM
Jayakrishna 🇮🇳
+ 2
Dont know about segmentation but I can tell you about the 49. Characters are stored in computers using their ascii value. An ascii is an integer. When you use %d, the compiler gives you the integer value stored in the char.
10th Feb 2020, 6:36 PM
Salman Nazeer
Salman Nazeer - avatar
+ 2
Please look into my correction for your code.
10th Feb 2020, 6:40 PM
Salman Nazeer
Salman Nazeer - avatar
11th Feb 2020, 3:56 PM
Programmer Raja
Programmer Raja - avatar