使用函数 c++ 打印结构指针

Print struct pointer using function c++

问题是程序在使用指针时不打印任何值,我找了很多好像都没有解决办法。有什么想法吗?

#include <iostream>
using namespace std;

struct Brok{
    string name;
    int age;

    void pt(){
        cout << "Name : " << name << "\nAge : " << age;
    }
};


int main()
{
    Brok *a1;
    a1->name = "John Wick";
    a1->age = 46;
    a1->pt();

    return 0;
}

输出:



...Program finished with exit code 0
Press ENTER to exit console.

您需要分配对象a1“指向”,例如Brok *a1 = new Brok();.

示例:

/*
 * SAMPLE OUTPUT:
 *   g++ -Wall -pedantic -o x1 x1.cpp
 *   ./x1
 *   Name : John Wick
 *   Age : 46
 */
#include <iostream>
using namespace std;

struct Brok{
    string name;
    int age;

    void pt(){
        cout << "Name : " << name << "\nAge : " << age;
    }
};


int main()
{
    Brok *a1 = new Brok();
    a1->name = "John Wick";
    a1->age = 46;
    a1->pt();

    return 0;
}

布鲁克*a1?它没有设置为刚刚声明的任何内容.....

这是将另一个变量的地址分配给指针的方式:

pointer = &variable;