+ 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);
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..
+ 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.
+ 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.
+ 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?
+ 3
~ swim ~
Thanks for letting me know that..
+ 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.
+ 2
Please look into my correction for your code.