I am working on a stacks assignment in which we are creating a stack of pointers to structs called Data. Our professor is trying to help us develop good habits in regards to security in designing a program, which is why we have a stack of pointers to structs rather than a stack of the structs themselves.
I know that typically when de-referencing a pointer, you do it with an asterisk. Example:
int x = 5;
int* xptr = &x;
cout << *xptr << endl;
My understanding is that the above code would create a var x with the value 5, then a pointer that store the address of the var x, and then by printing *xptr, you are de-referencing the pointer, which causes the printed output to be the value of x (5). If I'm incorrect anywhere so far, let me know.
So now onto the stack class, my professor created the .h file for us and we have these attributes:
int top; // this is your top index
Data *stack[STACK_SIZE];
My understanding of the stack is that we have an array of pointers to Data structs (as indicated by the * prior to the name "stack") and the stack is literally named "stack". My question is: when I need to pop a Data struct off (I'm calling it popData) and I want to assign its value, I know that I can't just do popValue = stack[top] because popValue is of type Data, which can't receive an assignment of a pointer.
I was thinking I could do this:
Data popData;
*Data popDataPtr;
popDataPtr = stack[top];
popData = *popPtr;
I am thinking that logically this would work, but I was wondering if there is syntax for de-referencing the ptr and assigning it in the same line. I'm thinking either:
popData = *stack[top];
or
popData = stack[*top];
But I'm not sure what's correct. I can't seem to find an example online of this. Thanks in advance to anyone who can help.