现实生活中使用的常量指针

Constant pointers used in real-life

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

亲爱的堆栈溢出社区

我试图更好地理解指针,遇到了一个问题:

问:我们什么时候可以使用常量指针?给出一个真实场景的示例并给出一些代码。

我在尝试查找和理解常量指针代码在现实生活中的使用位置以及所涉及的代码时遇到了问题。我不确定我的代码是否符合我的示例的标准。我尝试了以下方法:


我的回答:

1- 定义:

常量指针是无法更改其所持有地址的指针。

2-示例:

如果您想查找存储在手机联系人中的特定号码。而不是复制整个联系人列表(及其号码(,然后检查该特定号码。只需按住其地址并检查原始联系人列表(如果该号码在那里(。

3- 代码:

int main(){
     const int* number = 032 ... ;
     bool found = false;
     Vector<int> contactList = { 031 ... , 032 ... , 072 ... };
     for(int i=0; i < contactList.size(); i++){
         if( *number == contactList[i]){
         valid = true;
         }
     }
     if(valid){
        cout<< "Number found"<<endl;
     } else{
        cout<< "Number NOT found"<<endl;
     }
  }
首先,

常量指针和常量指针是不同的东西:

常量

指针本身是常量。除了它已经指向的东西之外,它不能指向任何其他东西,因为它指向的东西可能会被改变:

int i = 5;
int *const p1 = &i; // a const pointer
++*p1; // valid code. i is now 6
int j = 0;
p1 = &j; // error

指向 const 本身的指针可能指向不同的东西,但它假设它指向的所有内容都是 const,因此它不允许更改它们:

int i = 5;
const int * p2 = &i; // a pointer to const
++*p2; // error
int j = 0;
p2 = &j; // valid code. p2 is now pointing to j

我假设你的问题是"为什么有人会使用假设一切都是常量的指针?可能有很多原因。其中之一是,当您将const int *视为函数参数时,您知道此函数不会弄乱您的变量。函数返回后,它将保持不变。这基本上就是我们使用 const 的原因。我们可以不更改变量,但是通过将它们声明为const,我们知道编译器将确保我们的变量不会因错误或误解或其他任何事情而更改。

指向常量或常量指针的指针?

您需要注意定义常量指针的方式。 因为常量指针不是指向常量的指针。

 static int table[10]; 
 const int* number = table;    // non const pointer to const
 int * const number2 = table;  // const pointer to non const
 number++;             // this is allowed  because the pointer is not const 
 *number += 2;         // this is NOT allowed because it's a pointer to const
 number2++;            // this is NOT allowed because the pointer is const
 *number2 +=2;         // this is allowed because the const pointer points to a non const

顺便说一下,小心前导 0,因为它们意味着八进制表示法:

 cout << 032 <<endl;   // displays 26 in decimal since 032 is octal notation

指针、地址和值

请注意指针和指向的值之间的区别。 幸运的是,C++禁止这样做可以保护您:

 const int* number = 032;    // compiler error 

如果要保留指向特定值的指针:

 int myvalue=032; 
 const int* number = &myvalue;     // ok as long as you remain in scope

指向矢量元素时的注意事项

最后但并非最不重要的一点是,如果您想使用指向矢量元素的指针,请注意,在某些情况下,矢量元素的地址可能会更改(指针无效(,例如当矢量需要增长时。

您要执行的操作示例

现在让我们把所有这些放在一起,这里有一个稍微修改的程序:

const int * number;    // const to avoid accidental overwrite
int search;            // value to search for
cout<<"What number are you looking for ? "; 
cin>>search;  
for(int i=0; i < contactList.size(); i++){
     if( contactList[i] == search){  // compare values
         number = &contactList[i];   // set pointer
         found = true;
     }
 }
 // if the vector is not modified,  you may use the pointer.  
 if(found){
    cout<< "Number found: "<< *number <<endl;
 } 
 else{
    cout<< "Number NOT found"<<endl;
 }