Print struct pointer using function c++

The problem is that the program does not print any values when using the pointer, I searched a lot and there seems to be no solution. any ideas?

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

Output:



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

>Solution :

You need to allocate the object a1 is "pointing to", e.g. Brok *a1 = new Brok();.

EXAMPLE:

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

Leave a Reply