Reputation: 31
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.
Upvotes: 2
Views: 79
Reputation: 448
I would recommend trying it next time by yourself to see which of your examples would work.
You can have the assignment in one line, and I would recommend also adding parentheses in complex expressions like this, so you don't have to memorize operator precedence:
Data popData = *(stack[top]);
Small comment regarding your other code, this will not compile:
*Data popDataPtr;
The syntax for a pointer to a Data
is no different from a pointer to an int
, which you had before:
int* xptr = &x;
So to make the code from your example work, you actually need
Data* popDataPtr;
There is a great rule of thumb in C++: read the declarations from right to left, for example:
Data * const ptr1; // ptr1 is a constant pointer to a Data
const Data * ptr2; // ptr2 is a pointer to Data which is const (or just to a constant Data)
Data * arr1[]; // arr1 is an array of pointers to Data.
Upvotes: 2
Reputation: 3187
popData = *stack[top]; // this will do the trick
Here you are accessing the pointer that you want and you are then dereferencing that pointer and storing the data pointed to in popData
Upvotes: 1