2

I'm testing something that we do in school. I have a struct MyStruct and two pointers, but when I want to work with the pointer I get this error for both pointers:

uninitialized local variable 'p' used

struct MyStruct {
    int id;
    double value;
};

MyStruct *p, *q;
double z = 10;
double y = 16.17;
(*p).value = z;
(*q).value = y;
cout << (*p).value << " " << (*q).value << endl;
3
  • Why are you even using pointers here? Commented Mar 8, 2018 at 17:10
  • Because our teacher is going to ask us questions like "what is the result of operation p=q.." and stuff like that.. Commented Mar 8, 2018 at 17:12
  • @Honza -- enter this into the search box above: "uninitialized pointer c++". Variations of this question get asked a lot. This one may help you: stackoverflow.com/questions/32936349/…. If you do need to ask questions like this in the future, include enough that the snippet will compile if we cut & pasted it. (Hope that wasn't too toxic). Commented Mar 8, 2018 at 17:12

2 Answers 2

1

Your p and q pointers aren't initialized, so attempting to dereference them is undefined behaviour!

If you really want to use pointers here, make sure you have them point to valid memory. For example:

struct MyStruct {
    int id;
    double value;
};

MyStruct *p = new MyStruct, *q = new MyStruct; // <- allocate memory with `new`
double z = 10;
double y = 16.17;
(*p).value = z;
(*q).value = y;
cout << (*p).value << " " << (*q).value << endl;

delete p; // <- free memory with `delete`
delete q;
Sign up to request clarification or add additional context in comments.

Comments

1

You need to allocate the memory for both p and q structs. What you are doing is trying to access some pointer that doesn't point anywhere.

Add these two lines and don't forget to delete p and q when you're done working with them

p = new MyStruct;
q = new MyStruct;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.