常量字符* a[4];我可以更改 a[] 值吗?
const char* a[4]; can I change a[] values?
我认为 const char* a[4] 意味着 a[] 的元素是 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;
}
}
您正在声明一个包含 2 个指向 const char 的指针的数组。你可以改变指针(让它们指向不同的东西),但你不能改变它们指向的内存。所以你可以做
a[0] = "hello world";
但是你不能通过稍后做
来将 "hello" 大写
a[0][0] = 'H';
const
限定符以非常直观的方式应用。所以我们有:
1) 指向可变内容的两个指针的可变数组:char* a[2]
:
a[0] = nullptr; //Ok
a[0][0] = 'C'; //Ok
2) 指向不可变内容的两个指针的可变数组:const char* a[2]
:
a[0] = nullptr; //Ok
a[0][0] = 'C'; //Error
3) 指向可变内容的两个指针的不可变数组:char* const a[2]
:
a[0] = nullptr; //Error
a[0][0] = 'C'; //Ok
4) 指向不可变内容的两个指针的不可变数组:const char* const a[2]
:
a[0] = nullptr; //Error
a[0][0] = 'C'; //Error
注意,在 3 和 4 的情况下,a
需要初始化程序(因为 const 变量无法更改)。示例:
const char* const a[2] =
{
ptr1,
ptr2
};
const char *a[4] with the combination priority.
^^^^^^^^^^1
^^^^^^^^^^^^^^^^2
这意味着你有 4 个字符指针空间,每个字符指针空间都可以指向一个字符数组。 "const" 限定符指定您只能读取但不能修改。
例如:
char str1[] = "hello"
char str2[] = "good"
const char *ptr = str1;
cout << ptr << endl; // is correct for read
*(ptr + 1) = "a"; // it will alert an error by the compiler, you can't modify
ptr = st2; // is correct, point to another char array(or string)
cout << ptr << endl;
我认为 const char* a[4] 意味着 a[] 的元素是 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;
}
}
您正在声明一个包含 2 个指向 const char 的指针的数组。你可以改变指针(让它们指向不同的东西),但你不能改变它们指向的内存。所以你可以做
a[0] = "hello world";
但是你不能通过稍后做
来将 "hello" 大写a[0][0] = 'H';
const
限定符以非常直观的方式应用。所以我们有:
1) 指向可变内容的两个指针的可变数组:char* a[2]
:
a[0] = nullptr; //Ok
a[0][0] = 'C'; //Ok
2) 指向不可变内容的两个指针的可变数组:const char* a[2]
:
a[0] = nullptr; //Ok
a[0][0] = 'C'; //Error
3) 指向可变内容的两个指针的不可变数组:char* const a[2]
:
a[0] = nullptr; //Error
a[0][0] = 'C'; //Ok
4) 指向不可变内容的两个指针的不可变数组:const char* const a[2]
:
a[0] = nullptr; //Error
a[0][0] = 'C'; //Error
注意,在 3 和 4 的情况下,a
需要初始化程序(因为 const 变量无法更改)。示例:
const char* const a[2] =
{
ptr1,
ptr2
};
const char *a[4] with the combination priority.
^^^^^^^^^^1
^^^^^^^^^^^^^^^^2
这意味着你有 4 个字符指针空间,每个字符指针空间都可以指向一个字符数组。 "const" 限定符指定您只能读取但不能修改。
例如:
char str1[] = "hello"
char str2[] = "good"
const char *ptr = str1;
cout << ptr << endl; // is correct for read
*(ptr + 1) = "a"; // it will alert an error by the compiler, you can't modify
ptr = st2; // is correct, point to another char array(or string)
cout << ptr << endl;