DEV Community

Nakidai
Nakidai

Posted on

2 1 1 1 1

Assigning strings in C

#c
#include <stdio.h>
int main(void)
{
    char *string = "Wello, world!";
    string[0] = 'H';
    puts(string);
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
labnan profile image
Labnan

Great article!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay