469,960 Members | 2,357 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,960 developers. It's quick & easy.

Please explain this behaviour related to pointer

Hi All,

Here is the code which generates Segmentation Fault. Can anyone explain why the third printf fails and the first printf works?

Expand|Select|Wrap|Line Numbers
  1. main() 
  2.    char ch[7]={"Hello"}; 
  3.    char *p; 
  4.    p=ch; 
  5.    printf("Character is %c\n", *p); 
  6.    printf("Character is %s\n", p); 
  7.    printf("Character is %s\n", *p); 
Output:

Character is H
Character is Hello
Segmentation Fault(coredump)

But Why *p could not fetch the entire string when I say %s in the third printf statement? Why same *p works for first printf?

Please explain...

Thanks & Regards
Sathish Kumar
Oct 27 '07 #1
3 1193
Ganon11
3,652 Expert 2GB
When you use the %s output modifier, I assume printf expects a char* (as that would point to a series of characters, or a string). But you passed it *p, which is a character. A character is not a string, and so the printf() statement fails.

Also, why don't you have a terminating \0 character at the end of ch? I'm surprised your second printf() statement works.
Oct 27 '07 #2
Banfa
9,065 Expert Mod 8TB
Also, why don't you have a terminating \0 character at the end of ch? I'm surprised your second printf() statement works.
Ganon you banana, have you got so into C++ you have forgotten C string syntax? "Hello" implicitly includes the '\0' character at the end of it and since the array it is being assigned to is long enough for the 6 characters in that string (it is 7 characters long) it wont be a problem.
Oct 27 '07 #3
Ganon11
3,652 Expert 2GB
Ganon you banana, have you got so into C++ you have forgotten C string syntax? "Hello" implicitly includes the '\0' character at the end of it and since the array it is being assigned to is long enough for the 6 characters in that string (it is 7 characters long) it wont be a problem.
Impossible! I can't forget something I never learned!

(never learned C except from TSDN :D)
Oct 27 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by Abhish | last post: by
2 posts views Thread by Gerhard Esterhuizen | last post: by
22 posts views Thread by Jaspreet | last post: by
12 posts views Thread by Eric Lilja | last post: by
285 posts views Thread by Sheth Raxit | last post: by
11 posts views Thread by Pranav | last post: by
reply views Thread by Andrew Poelstra | last post: by
reply views Thread by rainxy | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.