我很难理解指针

I am having difficulty understanding pointer

我正在尝试一些指针练习。 在代码末尾,当 a=b 时,我尝试打印 p 指向的值和地址,应该是 - a 的地址和第二个 2.but 结果为空。可能是什么问题?

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
    cout << "Hello World" << endl;

    int * p;
    *p = 22;
    //p=9;

    int a =1;
    int b = 2;

    //p = &a;

    //*p = 24;

    cout << p << " Pointer with no address to" << endl;
    cout << *p << endl;

    //pointer p saves the address of a in p
    p=&a;


    //should show the address of a
    cout << p << " Pointer with address to a" << endl;
    //should show the value of a
    cout << *p << endl;

    a=b;


    cout << p << endl;
    cout << *p ;

    return 0;
}

*p = 22 不会 使 p 指向数字 22.

为此,您需要先在某处初始化该值 22

int i = 22;

然后你可以让p指向i:

p = &i;

去掉*p = 22,取消注释第一个p=&a(删除第二个),它应该运行正常。


顺便说一句,想想什么是指针 - 它通过第二个值的内存地址指向另一个值。

所以,*p = 22 没有任何意义,指针没有内存地址可以乱用。 (您可能希望将其初始化为空指针 - int *p = NULL

一旦p=&a,就意味着变量p保存了a的内存地址。您不需要每次更改 a 时都重新分配它。无论其中的值是多少,您都可以通过 *p.

访问它