Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need help changing single character in char*

Tags:

c++

pointers

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 *testpa2 = &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?

like image 811
nick Avatar asked Dec 06 '22 21:12

nick


1 Answers

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.

like image 84
John Zwinck Avatar answered Dec 23 '22 00:12

John Zwinck