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

时间:2019-03-23 13:58:46

标签: c++ pointers

尊敬的Stackoverflow社区

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

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

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


我的回答:

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;
     }
  }

2 个答案:

答案 0 :(得分:1)

首先,const指针和指向const的指针是不同的:

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

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的指针?”。可能有很多原因。其中之一是,当您将const int *视为函数参数时,便知道此函数不会弄乱您的变量。函数返回后,它将保持不变。这本质上就是为什么我们仍然使用const的原因。我们不能只改变变量,而是通过将它们声明为const,我们知道编译器将确保我们的变量不会因错误,误解或其他任何原因而改变。

答案 1 :(得分:1)

指向const或const指针的指针吗?

您需要小心定义const指针的方式。因为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;
 }
相关问题