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!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (1)

Collapse
 
labnan profile image
Labnan •

Great article!

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

đź‘‹ Kindness is contagious

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

Okay