By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,002 Members | 2,157 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,002 IT Pros & Developers. It's quick & easy.

Please explain this behaviour related to pointer

P: 34
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
Share this Question
Share on Google+
3 Replies


Ganon11
Expert 2.5K+
P: 3,652
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
Expert Mod 5K+
P: 8,916
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
Expert 2.5K+
P: 3,652
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.