There are a couple of things going on here.
char *Type = new char[10];
This create a char*
pointer named Type
and initializes it to point to the first element of a newly allocated 10-element array.
Type = "Access"; // ERROR
This assignment doesn't do what you think it does. It doesn't copy the 6-character string "Access"
(7 characters including the terminating '\0'
) to the array you just created. Instead, it assigns a pointer to the first element of that array into your pointer Type
. There are two problems with that.
First, it clobbers the previous value of Type
. That 10-character array you just allocated now has nothing pointing to it; you can no longer access it or even deallocate it. This is a memory leak.
This isn't what the compiler is complaining about.
Second, a string literal creates a statically allocated const array ("statically allocated" meaning it exists for the entire execution of your program). Type
is not declared with a const
qualifier. If the compiler allowed you to point Type
to the string "Access"
, you could use that pointer to (attempt to) modify it:
Type = "Access";
Type[0] = 'a'; // try to change the string to "access"
The purpose of const
is to prevent you from modifying, or even attempting to modify, things that are read-only. That's why you're not allowed to assign a non-const pointer value to a const pointer object.
Since you're programming in C++, you're probably better off using std::string
.