Need help changing one character in char *

I am returning to C ++ and referring to pointers and much more, however I was hoping that I could understand why this code segment was giving a bus error.

char * str1 = "Hello World";
*str1 = '5';

ERROR: Bus error: (

And in general, I am wondering how to change the value of a single character in cstring. Because I understand that * str = '5' should change the value that str points to from "H" to "5". Therefore, if I printed the line, he would read: "5ello World".

In an attempt to understand, I wrote this piece of code too, which works as expected;

char test2[] = "Hello World";
char *testpa2 = &test2[0];
*testpa2 = '5';

This gives the desired result. So what is the difference between testpa2 and str1? Don't they both point to the beginning of a series of characters with a null character?

+3
source share
3 answers

char *str = "Hello World";, , . const char*, (oops).

char str[] = "Hello World;", , ( ) , . .

+5

.: -)

, .

( , , , -), .

+4

, undefined.

2.13.4.2

(.. ) . undefined.

In your second example, you used the string literal initialization defined in 8.5.2.1

A char array (regular char, signed char or unsigned char) can be initialized with a string literal (optionally enclosed in curly braces); The wchar_t array can be initialized with a wide string literal (optionally enclosed in curly braces); subsequent characters of a string literal initialize a member array.

+3
source

All Articles