santosh
santosh

Reputation: 11

array of char and pointer to char in c++

The following two programs are really confusing me. In the first program I use const char* and I can reassign the string. In the second example I use a const char[] and now I can no longer reassign the string. Could someone please explain why this is?

#include <iostream>
using namespace std;

const char* x {"one"};
void callthis(const char t[]);

int main()
{
    callthis("two");

    return 0;
}
void callthis(const char t[]){

    t=x;        // OK

    // OR

 // x=t;    // OK
}

Second:

#include <iostream>
using namespace std;

const char x[] {"three"};
void callthis(const char* t);

int main(){
    callthis("four");

    return 0;
}

void callthis(const char* t){
    x=t;    // error: assignment of read-only variable 'x';
    // error : incompatible types in assignment of
    // 'const char*' to 'const char [6]'
}

Upvotes: 0

Views: 100

Answers (1)

NathanOliver
NathanOliver

Reputation: 180415

An array is not a pointer. Lets cover that again: An array is not a pointer

Arrays cannot be assigned to. Once the are declared if the are not initialized at that time the only way to set the value of the array is to iterate to each element and set its contents. The const on the array is a red hearing, if we were to use

char x[] {"three"};
//...
void callthis(const char* t){
    x=t;
}

We would still get an error like:

error: array type 'char [6]' is not assignable

The reason the first example works is that pointers can be assigned to and a const char * is not a constant pointer but a pointer to a constant char. Since the pointer is not const where can change what the pointer points to. If you were to use

const char * const x {"one"};

Then you have received an error along the lines of

error: cannot assign to variable 'x' with const-qualified type 'const char *const'

I also noticed you are using using namespace std; in you code. In small examples it doesn't really hurt anything but you should get into the habit of not using it. For more information on why see: Why is “using namespace std” in C++ considered bad practice?

Upvotes: 4

Related Questions