DEV Community

Nakidai
Nakidai

Posted on

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!

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (1)

Collapse
 
labnan profile image
Labnan

Great article!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay