Why can a char * be assigned to a string?

Sorry for the poor wording. This would make more sense.


 
   char * Greeting = "Hello World!"; // This works 


You normally cannot assign values to pointers.
Take int for example.

 
   int * magicNumber = 42; // This will not work 


Is "Hello World?" being stored on the heap or on the stack?
I thought it was on the heap but this does not work.
 
   delete [] Greeting; // This will break the program 


Thank you!
Last edited on
1) It is technically illegal in modern C++. Correct way is const char * Greeting = "Hello World!";
2) You can assign values to pointers. You just need to make sure types are compatible:
1
2
int x;
int* magic = &x;

3) type of string literal "Hello World!" is const char[13] which per array-to-pointer conversion rules can be converted to const char*
3)
Is "Hello World?" being stored on the heap or on the stack?
It is irrelevant. It can be stored anywhere where compiler will see fit (and there technically no stack and heap in c++ standard). What important that it has static storage duration.
this does not work.
Because it was never allocated with new[]. Trying to delete something which does not have dynamic storage duration yields undefined behavior. For example, crash.
int * magicNumber = (int*)42;
Technically, this works just fine. The problem is that it isn't doing what your brain thinks it is.

'magicNumber' is a pointer to int, and you assign it the address '42', which is almost guaranteed to be a location your program is not permitted to access.

Hence, when you try to run the program, any attempt to access or modify *magicNumber causes abnormal termination.

Hope this helps.

edited for an appropriate cast.
Last edited on
which is almost guaranteed to be a location your program is not permitted to access.
On Windows it is guaranteed — low 64kb are always non-pageable memory.
I can't say it is guaranteed on every extant system, though...
int * magicNumber = 42;
Technically, this works just fine. The problem is that it isn't doing what your brain thinks it is.

It'll work just fine with an appropriate cast. Fortunately, it won't compile as written.
Okay, fixed. It'll still cause abnormal termination, and shouldn't be done.
Topic archived. No new replies allowed.