Difference between char* and char[]

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Jan 2008
Posts: 8
Reputation: Dark_Knight is an unknown quantity at this point 
Solved Threads: 0
Dark_Knight's Avatar
Dark_Knight Dark_Knight is offline Offline
Newbie Poster

Difference between char* and char[]

 
0
  #1
Jan 15th, 2008
Hi. Below are two pieces of code. This first one works fine:
  1. char str[] = "Hello World";
  2. char *b;
  3. b = &(str[3]);
  4. *b = '3';
  5. printf("%s\n", str);

However this second one results in a segmentation fault.
  1. char *str = "Hello World";
  2. char *b;
  3. b = &(str[3]);
  4. *b = '3';
  5. printf("%s\n", str);

The difference is in the definition of the variable str. Why does one method work fine and the other result in a segmentation fault? When is it best to use a str[] definition and the *str definition?
Last edited by Dark_Knight; Jan 15th, 2008 at 12:13 am.
Live life on the edge ... you take up less room that way.
Reply With Quote Quick reply to this message  
Join Date: Oct 2007
Posts: 1,953
Reputation: Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of Duoas has much to be proud of 
Solved Threads: 214
Featured Poster
Duoas's Avatar
Duoas Duoas is offline Offline
Posting Virtuoso

Re: Difference between char* and char[]

 
0
  #2
Jan 15th, 2008
The first is local data you can edit (since the array is local data).

The second is a local pointer to global, static (constant) data. You are not allowed to modify constant data.

If you have GNU C, you can compile with -fwritable-strings to keep the global string from being made constant, but this is not recommended.
Reply With Quote Quick reply to this message  
Join Date: Jun 2005
Posts: 1,496
Reputation: WolfPack has a spectacular aura about WolfPack has a spectacular aura about WolfPack has a spectacular aura about 
Solved Threads: 104
Moderator
WolfPack's Avatar
WolfPack WolfPack is offline Offline
Mentally Challenged Mod.

Re: Difference between char* and char[]

 
0
  #3
Jan 15th, 2008
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC