2

Code A:

char* str="hello";
str[2]='!';
printf("%s\n", str);

In this code, the program compiles and runs but get a run-time error: "

However, if one writes the following code (Code B):

char str[10]="hello";
str[2]='!';
printf("%s\n", str);

Then, everything is fine. The program runs and outputs "he!lo".

I don't understand how the difference between code A and code B affect the behaviour of the compiler.

As far as I know, a pointer to an array points to the first element in the array (meaning, to the place where the character 'h' is located, and the elements of any array can change using the line: str[2]='!'; In code B, this line works fine! So... Why isn't it good in code A ?

user3189985
  • 189
  • 5
  • 14

3 Answers3

1

The second one creates 10 bytes on the stack (which is writable) and puts the hello and an ending zero in that allocate. The first one creates a pointer on the stack which points to a "hello" string located somewhere. In yours case it probably created it in memory not marked as writable so your program crashed when you ran it.

Brian Walker
  • 8,658
  • 2
  • 33
  • 35
  • This is the most mainstream and correct answer. I wanted to raise the point but Brian did that :) – Krypton Apr 02 '14 at 02:57
1
char* str="hello";

or

compiler, give me a reference to this sequence of chars in memory
do not care if it is read-only memory, just give me the damn pointer!

==

char str[10]="hello";

or

compiler, please allocate an array of 10 chars for me
and please initialize it with "hello".
Heeryu
  • 852
  • 10
  • 25
0

You are not allowed to modify, unless you declare it as str[] = "hello". Please look at this post: assign a string value to pointer

Community
  • 1
  • 1
cwhelms
  • 1,731
  • 3
  • 12
  • 14