Skip to content

Demonstrating why string literals (char*) are immutable and how char[] differs,and exploring types of strings based on sizes and their writting style#6

Open
Butcher3Years wants to merge 1 commit intoStrings---workingfrom
string---literals
Open

Demonstrating why string literals (char*) are immutable and how char[] differs,and exploring types of strings based on sizes and their writting style#6
Butcher3Years wants to merge 1 commit intoStrings---workingfrom
string---literals

Conversation

@Butcher3Years
Copy link
Copy Markdown
Owner

char* name = "Cherno";
name[2] = 'a'; // ❌ problem

❌ Why this fails (or crashes / UB)

"Cherno" is a string literal

String literals are stored in read-only memory

char* name just points to that memory

When you try to modify it → undefined behavior

👉 In modern C++, this is actually illegal.

Correct type would be:

const char* name = "Cherno";

Why char[] works
char name[] = "Cherno";
name[2] = 'a'; // ✅ works

✅ What’s different here?

"Cherno" is copied into a writable array

Memory is allocated on the stack

You own the memory → you can modify it

Memory layout:

…] differs,and exploring types of strings based on sizes and their writting style
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant