1

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.
paulsm4
  • 114,292
  • 17
  • 138
  • 190
sorax
  • 63
  • 1
  • 8
  • 1
    You have a pointer that points to... *somewhere*. But most definitely not to a valid object – UnholySheep Nov 09 '21 at 17:07
  • Hint: pointers are variables that point to other variables. Which other variable does `a1` point to? – user253751 Nov 09 '21 at 17:09
  • "any ideas?" is generally far too vague a question to have a _correct answer_. That said, the comments above should be taken as a hint that you might not yet understand what a pointer is. – Drew Dormann Nov 09 '21 at 17:11
  • @DrewDormann Actually I'm not good enough at C++ and that's the problem – sorax Nov 09 '21 at 17:18
  • 2
    @sorax that's not an uncommon feeling! In the scope of this problem, think about 1) pointers _point to things_. 2) Where does your pointer `a1` point? – Drew Dormann Nov 09 '21 at 17:22
  • @DrewDormann yeah, I had to look at what is the cause, not just look at what in front of me – sorax Nov 09 '21 at 17:30
  • @sorax if you have more C++ work, you will find it much easier if you [turn on compiler warnings](https://godbolt.org/z/7jE41GGza) or try to [run your programmer in a debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). Either one would have told you the problem in this code. – Drew Dormann Nov 09 '21 at 17:46

2 Answers2

3

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;
}
paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

Brok *a1 ? Its not set to anything just declared .....

This is how you assign the address of another variable to a pointer:

pointer = &variable;