2

What happen when constant string assigned to constant character pointer(or character pointer)? ex:

const char* p="String";

how and where the compiler take this array .. heap memory ? and what different from it and :

char* p="String";

thanks.

Amr Ashraf
  • 419
  • 6
  • 19

2 Answers2

0

What happen when constant string assigned to constant character pointer(or character pointer)?

Nothing happens to the const string itself: a pointer to it is assigned to p, that's all.

how and where the compiler take this array .. heap memory?

It does not take it anywhere. String's data remains where it was, which is a compiler-specific thing.

and what different from it and : char* p="String";

The compiler is going to reject a program with the assignment of a literal to non-const, or warn you of a deprecated conversion, depending on the C++ version and/or compiler settings. If you try to modify p[...]'s content using the const declaration, the compiler is going to stop you. If you try doing the same without const, the program may compile, bit it would cause undefined behavior at runtime.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Good . But i didn't understand how a only pointer can hold a character array however a pointer hold only an adress to the first element in the array . So where is constant string being save ?! – Amr Ashraf Aug 06 '15 at 18:23
0

The string literal "String" is a static array of const char somewhere in your program, probably placed into a read-only part of the address space when the executable is set up by your OS.

When you assign const char *p = "String", then p is initialized with a pointer to that array of const char. So *p is 'S' and p[1] is 't', etc.

When you assign char *p = "String", then your compiler should reject that (perhaps you have insufficient diagnostic level set?). If you tell the compiler to accept it regardless, then you have a pointer to (modifiable) char pointing at the string literal. If you subsequently attempt to write through this pointer, you'll get no compiler error, and instead you are likely to see one of two problems runtime:

  1. (If the compiler/linker has placed the string literal into read-only memory) a signal is raised indicating memory access violation (SIGSEGV on Unix-like systems).
  2. (If the string literal is in writeable memory) other uses of the same string literal get modified, because the compiler is permitted to point them all at the same storage.
Toby Speight
  • 27,591
  • 48
  • 66
  • 103