const char*a [4]; 我可以更改[]值吗?

day*_*yup 2 c++ const

我认为const char*a [4]意味着[]的元素是const,所以我不能在初始化后改变它.但是,以下代码向我显示它们可以更改.我很困惑......这里的const是什么?

#incldue<iostream>  
#include<string>
    using namespace std;
    int main()
    {
            int order=1;
            for(int i=1; i<10;++i,++order){
                    const char* a[2];
                    int b = 10;
    //              a[0] = to_string(order).c_str();
                    a[0] = "hello world";
                    a[1] = to_string(b).c_str();
                    cout << a[0] << endl;
                    cout << a[1] << endl;
                    cout << "**************" << endl;
                    a[0] = "hello" ;
                    cout << a[0] << endl;
            }
    }
Run Code Online (Sandbox Code Playgroud)

Mat*_*jek 5

const限定符以非常直观的方式应用.所以我们有:

1)指向可变内容的两个指针的可变数组char* a[2]:

a[0] = nullptr; //Ok
a[0][0] = 'C'; //Ok
Run Code Online (Sandbox Code Playgroud)

2)指向不可变内容的两个指针的可变数组const char* a[2]:

a[0] = nullptr; //Ok
a[0][0] = 'C'; //Error
Run Code Online (Sandbox Code Playgroud)

3)指向可变内容的两个指针的不可变数组char* const a[2]:

a[0] = nullptr; //Error
a[0][0] = 'C'; //Ok
Run Code Online (Sandbox Code Playgroud)

4)指向不可变内容的两个指针的不可变数组const char* const a[2]:

a[0] = nullptr; //Error
a[0][0] = 'C'; //Error
Run Code Online (Sandbox Code Playgroud)

注意,在情况34中,a需要初始化器(因为const变量不能更改).例:

const char* const a[2] =
{
    ptr1,
    ptr2
};
Run Code Online (Sandbox Code Playgroud)