C Pointer to arrays

83 views Asked by At

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?

1

There are 1 answers

2
Daniel Kleinstein On
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.