C++, char* string modification [duplicate] - c++

This question already has answers here:
Program crashes when trying to set a character of a char array
(5 answers)
Closed 5 years ago.
I am new to C++.
I have a program:
#include <iostream>
int main()
{
char* str = "Test";
*str = 'S';
}
The question is, why *str = 'S' crashes the program?
As far as I know str must be pointing to the first character of the string (well, char array), so in theory I should be able to modify it.
Is it because the memory is read-only for defined constant values?
I am using gcc 5.3.0.

why *str = 'S' crashes the program?
Because you're not allowed to modify string literals. The C++ standard allows them to be stored in read-only memory.
In fact, if you enable compiler warnings, you get:
prog.cc:5:16: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
char* str = "Test";
^~~~~~
Always use const char* when pointing to string literals:

Related

ISO C++ forbids converting string to char* [duplicate]

This question already has answers here:
Why is conversion from string constant to 'char*' valid in C but invalid in C++
(4 answers)
C++ forbids converting a `string` constant to `char*` - Alphabets to Morse converting program [duplicate]
(2 answers)
Closed 2 months ago.
The below is just a brief part of my code. And when I run it, it gives me the warning that ISO C++ forbids converting string to char* for visual studio code and exits with code 1. Is there a way I can ignore the warning to run the code?
Class Airport
{
public:
Airport(char *code, char *name);
}
Airport::Airport(char *code, char *name)
{
airport_code = new char[20];
strcpy(airport_code, code);
airport_name = new char[20];
strcpy(airport_name, name);
}
int main() {
Airport *lax = new Airport("LAX", "LA");
}
I saw on other stackoverflow posts that changing char to const char will solve the problem. But because the values will need to be changed using other predefined functions, it won't be the answer that I need.

should the value of pointer always be an address? [duplicate]

This question already has answers here:
initializing char pointer as string vs other type pointers as arrays
(5 answers)
Initializing a char pointer C++ [duplicate]
(3 answers)
What is the type of string literals in C and C++?
(4 answers)
Closed 5 months ago.
so ive just begun learning about pointer basics and ive come across something im stuck on.
as the title says, should the value of the pointer must always be an address?
because i saw a line of code, which says otherwise:
char *text = "text";
this here is being used for the creation of a string, the other method is:
char text[] = "text";
which is pretty understandable.
could you guys explain to me what this line does exactly?
char *text = "text";
a pointer is being used but what does it do and point to? how can you use it to then access
the string created.
thanks.
"text" is a string literal. It is stored somewhere in memory and its address is used to initialise the pointer. You access the string as you would with any other pointer.
And as stated above
char *text = "text";
is not legal C++ (it is legal C) the correct C++ is
const char *text = "text";

why char * works with const only [duplicate]

This question already has answers here:
What is the type of string literals in C and C++?
(4 answers)
Closed 6 months ago.
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define nline "\n"
int main(){
//const char *p="hello world";
// court<<p;
char *p="hello world";
cout<<p;
}
C:\Users\Dell\AppData\Roaming\Sublime Text\Packages\User\cses2.cpp: In function 'int main()':
C:\Users\Dell\AppData\Roaming\Sublime Text\Packages\User\cses2.cpp:7:10: warning: ISO C++ forbids converting a string constant to 'char' [-Wwrite-strings]*
char *p="hello world";
^~~~~~~~~~~~~
"hello world" is a const char[12]. A c-array of 12 constant (!) characters (note that one is for the null terminator).
In early C++ standards it was allowed to get a char * to a string literal due to compatibility with C. Though, it was nevertheless forbidden to actually modify the characters of the string literal via the char *.
This changed in C++11 and since then string literals have proper const correctness.
If you do want a string that can be modified, then use a std::string. Note that the pointer you obtain from the literal is not a string, its just a pointer to a (non-modifiable) c-string. If you want a string rather than a pointer to one, you need to use a string.

Assigning String Literals to Char Pointers [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get rid of deprecated conversion from string constant to ‘char*’ warnings in GCC?
This assignment:
char *pc1 = "test string";
gives me this warning:
warning: deprecated conversion from string constant to 'char*'
while this one seems to be fine:
char *pc2 = (char*)("test string");
Is this one a really better way to proceed?
Notes: for other reasons I cannot use a const char*.
A string literal is a const char[] in C++, and may be stored in read-only memory so your program will crash if you try to modify it. Pointing a non-const pointer at it is a bad idea.
In your second example, you must make sure that you don't attempt to modify the the string pointed to by pc2.
If you do need to modify the string, there are several alternatives:
Make a dynamically-allocated copy of the literal (don't forget to free() it when done):
char *pc3 = strdup("test string"); /* or malloc() + strcpy() */
Use an array instead of a pointer:
char pc4[] = "test string";
That depends on whether you need to modify the string literal or not. If yes,
char pc1[] = "test string";

Why string literals are allowed to be assigned to pointer of type char * in C++ [duplicate]

This question already has answers here:
how is char * to string literal valid?
(5 answers)
Closed 5 years ago.
Using visual studio, I declared a pointer of type char * and assigned to it a string literal. I then hovered the mouse over the string literal and it displayed its type: (const char [4])"abc".
How is this allowed? it compiles without warnings or errors, whilst assigning to the pointer an array of type const char [] fails, for obvious reasons, with an error message:
a value of type "const char *" cannot be assigned to an entity of type "char *"
So, why is it allowed for string literals?
int main(void)
{
char *p = "abc"; // no error here
const char str[] = "abc";
//p = str; This line generates an error
return 0;
}
EDIT: answer updated to incorporate info from Story Teller's comment.
In the olden days, const didn't exist, and people wrote things like char* p = "abc" all the time. As long as the didn't then do something like p[0] = 'z', their program worked. To remain compatible with such code, some compilers allow string literals to be assigned to non-const pointers if you don't ask the compiler to be super-strict. If you take advantage of this feature, you still should not ACTUALLY modify the string.