常量指针数组
array of constant pointers
好的,我知道这是无效的
char char_A = 'A';
const char * myPtr = &char_A;
*myPtr = 'J'; // error - can't change value of *myP
[因为我们声明了一个指向常量字符的指针]
为什么这是有效的?
const char *linuxDistro[6]={ "Debian", "Ubuntu", "OpenSuse", "Fedora", "Linux Mint", "Mandriva"};
for ( int i=0; i < 6; i++)
cout << *(linuxDistro+i)<< endl;
*linuxDistro="WhyCanIchangeThis";// should result in an error but doesnt ?
for ( int i=0; i < 6; i++)
cout << *(linuxDistro+i)<< endl;
感谢您的观看!
你写
*linuxDistro = "WhyCanIchangeThis";
这是完全有效的,因为linuxDistro
的声明是
const char *linuxDistro[6];
即它是一个由 6 个指向const char
的指针组成的数组。也就是说,您可以更改指针本身,但不能更改这些指针指向的字符。即,你不能编译
*linuxDistro[0] = 'B';
要获取字符串"Bebian"
,因为字符串包含常量字符...
您可能想要的是指向常量字符的常量指针数组:
const char *const linuxDistro[6];
*linuxDistro 仍然是一个指针,它是 linuxDistro[0],*linuxDistro="WhyCanIchangeThis"
它只是将指针更改为指向新地址,而不是修改旧地址中的内容,所以没问题。
如果你写**linuxDistro='a'
,它应该错误。
因为指针是存储内存地址的变量,如果指针const
指针会一直存储相同的内存地址,所以指针本身的值不能改变,但你没有说指针指向的值,根据你所拥有的,记录指向的值这是一个允许的操作。
因为char
不是char[]
,所以当你访问char[]
*
时,你访问它的第一个元素(Debian)。
当您移动指针(例如 +1 它)时,您将访问数组的下一个元素
这是更好地理解的好例子
#include <iostream>
using namespace std;
int main ()
{
int numbers[5];
int * p;
p = numbers; *p = 10;
p++; *p = 20;
p = &numbers[2]; *p = 30;
p = numbers + 3; *p = 40;
p = numbers; *(p+4) = 50;
for (int n=0; n<5; n++)
cout << numbers[n] << ", ";
return 0;
}
这将输出:
10, 20, 30, 40, 50,
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”