Security_Gate
Security_Gate

Reputation: 53

Passing values through files in C++

I'm still pretty new to C++, and I've been making progress in making my programs not look like a cluster-bleep of confusion.

I finally got rid of the various error messages, but right now the application is crashing, and I have no idea where to start. The debugger is just throwing a random hex location.

Thank you in advance.

#include <iostream>

using namespace std;

struct Value{
public:
    int Val;
}*pc;

#include "header.h"

int main () {
    cout << "Enter a value: ";
    cin >> pc->Val;
    cout << "\nYour value is " << pc->Val << ". ";
    system ("pause");
    return 0;
}

Upvotes: 3

Views: 121

Answers (5)

Gabe
Gabe

Reputation: 50493

#include <iostream>

using namespace std;

struct Value{
public:
    int Val;
}*pc;



int main () {


    pc = new Value();

    cout << "Enter a value: ";
    cin >> pc->Val;
    cout << "\nYour value is " << pc->Val << ". ";

    delete pc;

    system ("pause");
    return 0;
}

Upvotes: 0

Buhake Sindi
Buhake Sindi

Reputation: 89169

Variable pc is a pointer to the struct Value

Why don't you assign it first after the int main() declaration, like

pc = new Value();

By compiler default pc = NULL;. PS. In C++, you have to manage your own Garbage collection, so once you're done, do this:

delete pc; //It frees memory....

Hope this helps.

Upvotes: 0

Seva Alekseyev
Seva Alekseyev

Reputation: 61341

In your program, pc is not a struct - it's a pointer to the struct (because of *). You don't initialize it to anything - it points at some bogus location. So, either initialize it in the first line of main():

pc = new Value();

Or make it a non-pointer by removing *, and use . instead of -> for member access throughout the program.

Upvotes: 7

Klaim
Klaim

Reputation: 69672

You never initialized 'pc'. It's an undefined behaviour.

Upvotes: 3

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76531

pc is a pointer but you haven't given it valid memory to point to. You have a couple of choices.

You can use an object instead of a pointer and use it like an object:

struct Value{
public:
    int Val;
} c;

    ...
    cin >> c.Val;
    cout << c.Val;

You can keep as a pointer and have it point to something valid. Easiest way is to new an object and remember to delete it later:

int main()
{
    pc = new Value;

    ...

    delete pc;
}

Upvotes: 3

Related Questions