0

I am learning pointers in C. When I declare :

char c1[] ="hello";
c1[0] = c1[1];
printf("%s\n", c1);

It prints out eello

But when I do the following:

char * c2="hello";
c2[0] = c2[1];
printf("%s\n", c2);

it compiles in C# but the program crashes. Could you help me clarify what happens in the Stack when I execute the program?

MAK1647
  • 11
  • 3

1 Answers1

1
char c1[] ="hello";

In this line of code, c1 is declared as a local array of chars - and its contents will be placed on the stack of the function. Function stacks are modifiable and so c1[0] = ... will work.

char* c2 = "hello";

there's a subtle difference here - c2 is not an array, but a pointer to a string literal. Modifying it is undefined behavior per the standard - in practice, what usually happens is that the "hello" string gets placed in the executable's read-only .data section - and attempting to modify it triggers a page fault that crashes the program.

Daniel Kleinstein
  • 5,262
  • 1
  • 22
  • 39
  • I have 1 question that if we have: c1[]="hello"; and a pointer c2 point to string c1:char *c2=c1; this statement will ok : c2[0] = c2[1]; What is the different beetween statement c2[0] = c2[1];i mean in 2 case c2 still a pointer to the string – MAK1647 Sep 12 '21 at 17:59
  • The difference is a pointer to a string, and a pointer to a **string literal**. In `char* c2 = c1` - `c2` will point to `c1`'s memory, which is allocated **on the stack**. – Daniel Kleinstein Sep 12 '21 at 19:04