开发者

need help changing single character in char*

开发者 https://www.devze.com 2023-03-13 09:30 出处:网络
I\'m getting back into c++ and have the hang of pointers and whatnot, however, I was hoping I could get some help understanding why this code segment gives a bus error.

I'm getting back into c++ and have the hang of pointers and whatnot, however, I was hoping I could get some help understanding why this code segment gives a bus error.

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

ERROR: Bus error :(

And more generally, I am wondering how to change the value of a single character in a cstring. Because my understanding is that *str = '5' should change the value that str points to from 'H' to '5'. So if I were to print out str it would read: "5ello World".

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

char test2[] = "Hello World";
char *testp开发者_运维知识库a2 = &test2[0];
*testpa2 = '5';

This gives the desired output. So then what is the difference between testpa2 and str1? Don't they both point to the start of a series of null-terminated characters?


When you say char *str = "Hello World"; you are making a pointer to a literal string which is not changeable. It should be required to assign the literal to a const char* instead, but for historical reasons this is not the case (oops).

When you say char str[] = "Hello World;" you are making an array which is initialized to (and sized by) a string known at compile time. This is OK to modify.


Not so simple. :-)

The first one creates a pointer to the given string literal, which is allowed to be placed in read-only memory.

The second one creates an array (on the stack, usually, and thus read-write) that is initialised to the contents of the given string literal.


In the first example you try to modify a string literal, this results in undefined behavior.

As per the language standard in 2.13.4.2

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. The effect of attempting to modify a string literal is undefined.

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

A char array (whether plain char, signed char, or unsigned char) can be initialized by a string- literal (optionally enclosed in braces); a wchar_t array can be initialized by a wide string-literal (option- ally enclosed in braces); successive characters of the string-literal initialize the members of the array.

0

精彩评论

暂无评论...
验证码 换一张
取 消