[C++专栏]const和指针,星号的位置和效果总结

  • 实验概述

  • 该实验验证const关键字对指针指向和指向内容的影响,const关键字影响左边的关键字,如果const在最左侧,它将影响其右侧的关键字。
    const修饰左侧的*,则代表指针指向不可变
    const修饰左侧char关键字,代表指针指向的值不可变

  • CODE:

  • #include "stdafx.h"
    #include <iostream>
    using namespace std;
    unsigned int MAX_LEN = 11;
    int main()
    {
    int num = 11;
    char alpha = 'a';
    char strHelloworld[] = { "helloworld" };
    char const* pStr1 = "helloworld";             // const char*
    char* const pStr2 = strHelloworld; //为什么赋值字符串给一个指针         
    char const* const pStr3 = "helloworld";  // const char* const,该值与pStr1的值虽然相同,
                                                //但是由于可变性的差异,其内存地址不同
    int const* const pInt = &num;
    char const* const pChar = &alpha; //无论是字符还是整型数,都不可以像字符串一样直接赋值给指针
    cout << "content of string:" << endl;
    cout << strHelloworld << endl;
    cout << "address of string:" << endl;
    cout << &strHelloworld << endl;
    pStr1 = strHelloworld;//他的指针指向可变
        //pStr2 = strHelloworld;                            // pStr2不可改
        //pStr3 = strHelloworld;                            // pStr3不可改
        //unsigned int len = strnlen_s(pStr2, MAX_LEN);
    unsigned int len = 10;
        //cout << len << endl;
    for (unsigned int index = 0; index < len; ++index)
        {
            //pStr1[index] += 1;                               // pStr1里的值不可改
    pStr2[index] += 1;
            //cout << pStr2[index] << endl;
            //pStr3[index] += 1;                               // pStr3里的值不可改
        }
    cout << "content of string after the change:" << endl;
    cout << strHelloworld << endl;
    cout << "address of string after the change:" << endl;
    cout << &strHelloworld << endl;
    cout << "content of first item of post string(pStr1 influenced which is very annoying)" << endl;
    cout << "content_of_pStr1:";
    cout << *pStr1 << endl;
    cout << "content_of_pStr2:";
    cout << *pStr2 << endl;
    cout << "content_of_pStr3:";
    cout << *pStr3 << endl;
    system("pause");
    return 0;
    }

  • 实验结果

  • 字符串在修改前后内容发生了变化,但是地址没变 pStr1指向的内容不可变,但是却被同指向的pStr2给修改(因为2有修改权),这里就是一个指针的陷阱。
  • 一个比较大的坑

  • 当pStr1 = strHelloworld完成后,pStr2和pStr1的指向相同,也就是说其中一个指针修改内容后,另一个指针取值也会受到影响。

  •  

猜你喜欢

转载自blog.csdn.net/qq_33868661/article/details/110484529