Embed_Love
Embed_Love

Reputation: 21

Dealing with stack as struct element in cpp

I was working on a project recently and stumbled upon following situation

using namespace std;

//I have two structs, A basic struct as shown below
struct myAnotherStruct{
  int x;
  int y;
};

//A struct which embeds the stack of above struct type
struct myStruct{
  int a;
  float b;
  stack <myAnotherStruct> s;
};

//Somewhere else in the code, I created this
stack <myStruct> t;

//And performed following
struct myAnotherStruct var;
var.x = 10;
var.y = 20;

// But, when I performed the following operation, there was a core Dump!
t.s.push(var)

Now, My question are the following,

  1. Why core dump? should'nt the memory be allocated every time I add a new element? the var should be copied and storage class of the variable (var in my case) should not matter!

  2. Is it a good approach to do something like this? Because when I googled, I always got "stack of structs, Vector of structs" etc but not the other way (I.e, Struct of stacks).

Upvotes: 0

Views: 62

Answers (2)

DNT
DNT

Reputation: 2395

You are creating a stack of myStruct and not a myStruct instance.

//Somewhere else in the code, I created this
stack <myStruct> t;

You need to change it to:

myStruct t;

In the original code, the compiler should generate an error since stack has no member s here:

// But, when I performed the following operation, there was a core Dump!
t.s.push(var)

Upvotes: 2

Filip Henningsson
Filip Henningsson

Reputation: 31

The problem here is that you attempt to access an element of the stack without pushing an item to the stack like so:

myStruct m;  // Creates new myStruct object 
t.push(m);   // Adds object to stack

Furthermore the . operator does not automatically get the top object in the stack. If you want to add var to the member variable s in t, consider using t.top().s.push(var); to get the top element of the stack and then push car to the stack.

Upvotes: 1

Related Questions