![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#11 |
|
Newbie
Join Date: Apr 2008
Posts: 2
Rep Power: 0
![]() |
Re: char[] vs char*
Well... you are saying that it's not possible to change a string literal declared has a pointer but i've compiled this code and it worked:
#include <stdio.h>
int main() {
char *a = "hello";
printf("%s\n", a);
*a = 'a';
printf("%s\n", a);
return 0;
}When i run the program it shows "hello" followed by "aello". Can you tell me why can i modify the string pointed by "char *a"? ![]() |
|
|
|
|
|
#12 | |
|
Caffeinated Neural Net
Join Date: Jun 2005
Location: Dry west coast of Canada
Posts: 927
Rep Power: 4
![]() |
Re: char[] vs char*
Quote:
C Syntax (Toggle Plain Text)
Some systems will actually store the string in memory flagged as read-only, and a write access will raise a hardware exception, causing your program to crash. Others will not detect the access, but just because an illegal operation is not trapped, that does not make it okay. Remember that 'undefined' means your program may take any action, including acting in a manner you think is 'correct'.
__________________
A man's knowledge is like an expanding sphere, the surface corresponding to the boundary between the known and the unknown. As the sphere grows, so does its surface; the more a man learns, the more he realizes how much he does not know. Hence, the most ignorant man thinks he knows it all. - L. Sprague de Camp |
|
|
|
|
|
|
#13 |
|
Programming Guru
![]() Join Date: Apr 2005
Posts: 1,799
Rep Power: 5
![]() |
Re: char[] vs char*
And in support of lectricpharaoh's post: your code crashed, after printing the first line, when I attempted to run it.
|
|
|
|
|
|
#14 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,198
Rep Power: 5
![]() |
Re: char[] vs char*
The short answer, as electricpharoah said, is undefined behaviour.
For discussion another day, there are a few historic reasons the code will compile, although the runtime behaviour is not defined. This is due to very old (well before the first C standard) anomalies in the C language related to the relationship between string literals, arrays of char, and pointers to char, from days when the language did not support the const keyword. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| 25 ways to efficiently sort an array/list of integers | Jimbo | Software Design and Algorithms | 36 | Mar 3rd, 2008 6:31 AM |
| 500 Ways to Program Numbers 1 Through 10! | Sane | Coder's Corner Lounge | 637 | Jan 5th, 2008 10:15 PM |
| char * to char[] | titaniumdecoy | C++ | 6 | Jul 28th, 2006 12:53 PM |
| char[] problem | Kilo | C++ | 13 | Jun 19th, 2006 2:18 AM |
| Convert char[] to int | King | C++ | 18 | Jan 31st, 2006 3:55 PM |