Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading