0

Illegal Declaration

1.) char str = "hello"; //This code generates this error: [Error]invalid conversion from 'const // char* to 'char' 2.) char *str = "hello"; //This code generates [Warning] deprecated conversion from string // constants to 'char*' As provided in the SoloLearn Challenge 1, declaration 1 is not an illegal declaration, but 2 is an illegal one. However, both are not compile error free. I am asking for clarification on this. Thank you.

2nd Dec 2019, 7:35 AM
Abraham Almerol
Abraham Almerol - avatar
2 Respostas
0
As far as I know, both are valid in C but only the 2nd one is valid in C++, the 1st one requiring an explicit cast. The 1st one simply converts a pointer to a char. ( implicit conversion of pointers to integrals are illegal in C++ ) ( "hello" is a pointer to the real string ) The 2nd one is undefined behavior. The string "hello" is placed in read only memory, the linker is then responsible to mark the appropriate segment that it is in as 'read-only'. The operating system then deals with the rest. However, old operating systems like dos ( I believe ) has no concept of read only segments. So char* is sufficient for them. const char* is used these days, hense the deprecated warning. C/C++ has to take all of the operating systems into account. Simply causing an error here would cause them to not work on some operating systems.
2nd Dec 2019, 9:03 AM
Dennis
Dennis - avatar
0
1) you cant set a string on a char you can only do that with a single char like 'h'. If you want to define an array of chars to make a string you have to write: char str[] = "hello"; 2) you have to allocate memory before you use a pointer. But you can also point on an exciting memory location like an array. If you already have the array in 1 and want to point with pointer char *str2 on it you can write: char *str2; str2 = str; "str" is a pointer to the array so you don't need to use &. If you only have the pointer you maybe need to declare it first: char *str; str = "hello"; This could maybe work.
2nd Dec 2019, 9:13 AM
Jnn
Jnn - avatar