Reputation: 69
To be specific, I wanted to access multiple stacks with the purpose in mind to pop an element from one stack and push it into the other stack. So, I decided to access them using structures (struct). Consider the following code,
#define MAX 100
#include <stdio.h>
#include <string.h>
struct bag
{
int top;
int arr[MAX];
}harry,monk;
int pop(struct bag name);
void push(int data,struct bag name);
int main()
{
int i,temp;
harry.top=-1;
monk.top=-1;
push(3,harry);
push(1,harry);
push(1,harry);
push(4,harry);
temp=pop(harry);
push(temp,monk);
temp=pop(harry);
push(temp,monk);
for (i=0;i<4;i++)
printf("%d\t%d\n",harry.arr[i],monk.arr[i]);
return 0;
}
int pop(struct bag name)
{
int temp=name.arr[name.top];
name.top=(name.top)-1;
return temp;
}
void push(int data,struct bag name)
{
name.top=(name.top)+1;
name.arr[name.top]=data;
}
After analysing the code I found that each time I called function,
void push(int data,struct bag name)
the value of the name.top was changed to from -1 to 0 but was reverted back to -1 when it was called again. Hence any vaue assigned to harry.arr[harry.top] was ultimately assigned to the array harry.arr[-1]. So, anyone out there with any ideas?
Upvotes: 0
Views: 218
Reputation: 26
Use pointers, as now you are passing the parameters its gets copied as a local parameters inside the function thus original pass value remains unchanged .
Upvotes: 1
Reputation: 1936
I'm pretty sure it's because you are never actually modifying the 'stacks' in your functions. C is pass by value, meaning you will have to return the struct 'name' and set it equal to harry and monk within your main.
Such as:
harry = push(3,harry);
Additionally you can use pointers to simulate a pass by reference scenario like what you are intending with your current code.
Upvotes: 0