指向结构的指针包含指针

pointer to struct contains pointer

本文关键字:指针 包含 结构      更新时间:2023-10-16

我正在用 c++ 编写代码,但我在指针方面有问题,请帮助我!

错误为:网格中0x010613af处未处理的异常.exe: 0xC0000005:访问冲突读取位置0x00000004

#include <iostream>
using namespace std;
struct test{
    int test_num;
    int * test_ptr;
};
struct test1{
    int test1_num;
    test* test1_ptr;
};
void main()
{
    test1 tt;
    tt.test1_num=0;
    tt.test1_ptr=0;
    int  * t = tt.test1_ptr->test_ptr;
}

行:

int  * t = tt.test1_ptr->test_ptr

正在取消引用空指针。在以下行中将其设置为 null:

tt.test1_ptr=0;

有两件事是错误的:

  1. main 必须返回一个 int。
  2. 您正在取消引用空指针。

    int main()
    {
        test1 tt;
        tt.test1_num=0;
        tt.test1_ptr=0;
        int  * t // = tt.test1_ptr->test_ptr;
        return 0;
    }
    

如果tt.test1_ptr为0(即NULL),则不能尊重它,这是未定义的行为。

而不是tt.test1_ptr->test_ptr你应该使用tt.test1_ptr.test_ptr。请记住,运算符->返回指针指向的实际值,在您的情况下,地址 0 没有值/您无权访问该值。

首先,您将test1_ptr初始化为 0,然后在它指向任何内容之前尝试取消引用它。

tt.test1_ptr=0;
int  * t = tt.test1_ptr->test_ptr;