常量指针数组

array of constant pointers

本文关键字:数组 指针 常量      更新时间:2023-10-16

好的,我知道这是无效的

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,