Reputation:
Im having trouble understanding what this statement means, could someone explain it to me.
This is the struct I have:
struct dataT
{
int m;
};
struct stack
{
int top;
struct dataT items[STACKSIZE];
} st;
This is the statment i am confused about. I dont quite understand what it means:
st.items[st.top].m
Upvotes: 2
Views: 83
Reputation: 30489
st: An object of type struct stack
st.top: Top of stack
st.items: Array of stack items
st.items[st.top]: Top item of stack
st.items[st.top].m: memberm
of top item of stack
st
+-----------------------+
| top | st.top
+-----------------------+
| +-------------------+ |
| | |m| st.item[0]
| +-------------------+ |
+-----------------------+
| +-------------------+ |
| | |m| st.item[1]
| +-------------------+ |
+-----------------------+
. .
. .
. .
+-----------------------+
| +-------------------+ |
| | |m| st.item[STACKSIZE - 1]
| +-------------------+ |
+-----------------------+
if you push 3
and 5
into the stack, it would looks like (Stack is growing downward)
st
+-----------------------+
| 1 | st.top = 1
+-----------------------+
| 3 | st.item[0].m = 3
+-----------------------+
| 5 | st.item[1].m = st.item[st.top].m = 5
+-----------------------+
. .
. .
. .
+-----------------------+
| xxxxxxxxxxxxxxxxxxx |
+-----------------------+
Upvotes: 4
Reputation: 3277
This statement retrieves the value of the st.top
th element from struct stack
. In other words if your implementation increments in decrements the top
variable of struct stack
then it will retrieve the last pushed element.
Upvotes: 1
Reputation: 310910
In this statement
st.items[st.top].m
st denotes an object of type struct stack
because it was defined in this way
struct stack
{
//...
} st;
As st
is defined as having type of the structure then it has data member with name items
Here is the structure definition itself.
struct stack
{
int top;
struct dataT items[STACKSIZE];
};
So record st.items
means access to data member items
of object st
. This data member of the structure is defined as an array
struct dataT items[STACKSIZE];
with STACKSIZE
elements.
Thus record st.items[st.top]
means access to the element with index st.top
of the array items
. Each element of the array in turn has type struct dataT
This structure has data member m
struct dataT
{
int m;
};
Thus record
st.items[st.top].m
means access to data member m
of element with index st.top
of array items
that is in tirn a data member of object st
Upvotes: 2
Reputation: 3935
Dot (.) is used to access elements of a struct.
st.items - accesses items[STACKSIZE] array
st.top - accesses the top of st and used as the index
And items array contains dataT and you can access it's only element using
st.items[st.top].m
Upvotes: 3