#include <stdio.h>
int main(void)
{
char *string = "Wello, world!";
string[0] = 'H';
puts(string);
}
What will this program print after executing? "What a silly question, it will definitely print Hello, world!
", you probably think. Suddenly, the output is Segmentation fault (core dumped)
.
Now, look at another example:
#include <stdio.h>
int main(void)
{
char string[] = "Wello, world!";
string[0] = 'H';
puts(string);
}
And the code above successfully prints Hello, world!
and returns with 0
.
Why? These examples are so identical!
Well, yes. Almost. Arrays are not pointers, they are different types.
Most compilers store strings as constant variables. It means that you can't edit them. Also, it's important to understand that pointers in C are not arrays: string
from the first example is just some address in the memory. Summarizing that information, you can find out that in fact the string
from the first example only points to a read-only string, hence we can't modify it.
The second example works fine because it has string
of type array (that is, (almost always?) allocated on a stack) instead of a pointer. Compilers will copy the string "by value" to the string
array, meaning the read-only Hello, world!
is now allocated on a stack, and you can modify it as you want.
In the conclusion, you should know that pointers are not the same as arrays, and sometimes this difference can cause various errors. Be careful!
Top comments (1)
Great article!