2016-03-22 15 views
0

次の2つのプログラムは本当に私を混乱させます。最初のプログラムではconst char*を使用し、文字列を再割り当てできます。 2番目の例ではconst char[]を使用しましたが、文字列の再割り当てができなくなりました。誰かがこれがなぜなのか説明してもらえますか?charの配列とC++のcharへのポインタ

#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 
} 

セカンド:

答えて

4
#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]' 
} 

配列がポインタでありません。 配列がポインタではない

配列を割り当てることはできません。その時点で初期化されていないと宣言されると、配列の値を設定する唯一の方法は、各要素を反復してその内容を設定することです。最初の例は動作します

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

理由のポインタを割り当てることができるということである。我々は我々はまだのようなエラーが出るでしょう

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

を使用した場合、アレイ上のconstは、赤の公聴会でconst char *は定数ポインタではなく、定数へのポインタcharです。ポインタはconstではないので、ポインタが指しているものを変更することができます。あなたは

const char * const x {"one"}; 

を使用していたなら、あなたは、私はまた、あなたがあなたのコードでusing namespace std;を使用している気づい

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

のラインに沿って、エラーを受けています。小さな例では、それは本当に何かを傷つけることはありませんが、あなたはそれを使用しないという習慣に入るべきです。理由の詳細については、Why is “using namespace std” in C++ considered bad practice?

関連する問題