943,682 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Marked Solved
  • Views: 12745
  • C RSS
Jan 15th, 2008
0

Difference between char* and char[]

Expand Post »
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.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
Dark_Knight is offline Offline
8 posts
since Jan 2008
Jan 15th, 2008
0

Re: Difference between char* and char[]

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.
Featured Poster
Reputation Points: 1140
Solved Threads: 229
Postaholic
Duoas is offline Offline
2,039 posts
since Oct 2007
Jan 15th, 2008
0

Re: Difference between char* and char[]

Moderator
Reputation Points: 572
Solved Threads: 115
Mentally Challenged Mod.
WolfPack is offline Offline
1,559 posts
since Jun 2005

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: operation on tape using st driver
Next Thread in C Forum Timeline: [Error]Invalid combination of Opcode and Operands





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC