C - why can't I modify what is passed as an argument?

Cheetoz

[H]ard|Gawd
Joined
Mar 3, 2003
Messages
1,972
Code:
void ReverseString(char* String)  
{
  String[1] = 'a';
}

Code:
Program received signal SIGSEGV, Segmentation fault.
0x000000000040094c in ReverseString (String=0x400a74 "Hello") at main.cpp:33
33        String[1] = 'a';

is this real life? I swear anything beyond RISC assembly is so complicated- not worth it.
 
It looks like you are trying to modify a string literal, which is held in read-only memory.

Assume you have:
char *aString = "Hello"

This is a string literal and is essentially a constant:
const char *aString = "Hello"
would be the proper way to write the above.

If you were to pass aString into ReverseString as defined, you would be attempting to modify a constant, which is undefined.

Instead, you would want to define aString as:
char aString[] = "Hello"
 
Last edited:
It looks like you are trying to modify a string literal, which is held in read-only memory.

Assume you have:
char *aString = "Hello"

This is a string literal and is essentially a constant. If you were to pass aString into ReverseString, you would be attempting to modify a constant, which is undefined.

Instead, you would want to define aString as:
char aString[] = "Hello"

Thanks. If the compiler sets the first one as read only, whats the point of having "const" options :confused:
 
The const modifier serves several purposes.
Code:
const char * test1; // changeable pointer to constant character

char * const test2; // constant pointer to changeable character

const char  * const test3; // constant pointer to constant character
 
It's implementation specific, not mandatory, that *aString = "Hello" gets loaded into read-only memory.

But using const makes it more explicit and portable.

Edit: Basically, you need to look at the differences between passing char* and char[] in C.

When you pass char[] you are passing a pointer to the location of the first character in an array of string literals where the end is defined via the existence of the null termination character.

But when you pass char* you are passing a pointer to the string literal itself.

You cannot modify string literals, but you can modify pointers and arrays.

You may find the following blog post useful:
http://techblog.rosedu.org/arrays-vs-pointers.html
 
Last edited:
When you pass char[] you are passing a pointer to the location of the first character in an array of string literals where the end is defined via the existence of the null termination character.

But when you pass char* you are passing a pointer to the string literal itself.http://techblog.rosedu.org/arrays-vs-pointers.html

this is the most important part of your explanation (emphasis mine) and what really needs to be learned in order to appreciate this.
 
Back
Top