please tell WHY this propagates error?(segmentation fault)
I'm trying to change first character with the code(just an example)Code:char *a;
a="i'm A string!";
*a='I';//this line is logically wrong
---
thanks in advance
Printable View
please tell WHY this propagates error?(segmentation fault)
I'm trying to change first character with the code(just an example)Code:char *a;
a="i'm A string!";
*a='I';//this line is logically wrong
---
thanks in advance
Since a points to a string literal, and you are trying to change a char using a, you are trying to change a char literal. What you should do is along the lines of:
Code:char a[14];
strcpy(a, "i'm A string!");
*a = 'I'; // or a[0] = 'I';
To avoid this kind of runtime error, only assign string literals to const char *s (assuming a narrow character):
If you need to modify the string, either do as laserlight has shown, or use a std::string.Code:const char *a = "i'm A string!";
*a='I'; //this line is logically wrong, and fortunately doesn't compile
would you share more light on it?Quote:
Since a points to a string literal, and you are trying to change a char using a, you are trying to change a char literal.
i knew the solution i wanted to know more about that error
To avoid this kind of runtime error, only assign string literals to const char *s (assuming a narrow character):
If you need to modify the string, either do as laserlight has shown, or use a std::string.Code:const char * a = "i'm A string!";
*a='I'; //this line is logically wrong, and fortunately doesn't compile
String literals exist in a special segment of the executable that may not be modified at runtime. When you assign a string literal to a pointer, you are then pointing to that static memory, so dereferencing the pointer and trying to modify the string is an error.Quote:
Originally Posted by sepehr
Do you understand what I mean by "a points to a string literal"?Quote:
would you share more light on it?
i knew the solution i wanted to know more about that error
aha!that was what i wanted to know thanks alot hermit!Quote:
Originally Posted by Hermit
you DON'T have to repeat ! :P what i asked was clear!Quote:
Originally Posted by Hermit
To put it more simply, string literals are const. A string literal is anything between double quotes.Quote:
Originally Posted by sepehr
A little more detail: C++ takes a string literal, slaps '\0' character on the end of it, and then transforms it into a char array that cannot be changed, in other words the string literal becomes a const char array. Try this:
You should get an error that says something like:Code:int* p;
p = "hello";
That shows that the string literal is first converted to a char array before anything else happens.Quote:
error: cannot convert const char[6] to int*