0

This is the initial part of main function I used:

int main() {
int q;
struct ListNode* S = NULL;
scanf("%d\n",&q);
int i;
for (i=0;i<q;i++){
    int queryType;
    scanf("%d", &queryType);
    struct NumOp* j;
    struct NumOp k;
    if(queryType == 1){
        double num;
        scanf("%lf", &num);
        if(num>=1 && num<=100){
            k.type='n';
            k.num=num;
            k.op='\0';
            j=&k;
            Push(&S,j);
        }
    }

Now the issue is this would create a stack consisting of the last pushed element in all the nodes pushed by this time. On making certain changes the following code seemed to work fine. Could anyone tell me why this didn't work in first place.

int main() {
int q;
struct ListNode* S = NULL;
scanf("%d\n",&q);
int i;
for (i=0;i<q;i++){
    int queryType;
    scanf("%d", &queryType);
    struct NumOp* j = (struct NumOp*) malloc(sizeof(struct NumOp));
    if(queryType == 1){
        double num;
        scanf("%lf", &num);
        if(num>=1 && num<=100){
            j->type='n';
            j->num=num;
            j->op='\0';
            Push(&S,j);
        }

The explanation is what I m looking for.

  • Unrelated to your problem, but please read [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/) – Some programmer dude Jan 23 '19 at 14:08
  • Have you tried debugging your own code? https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ –  Jan 23 '19 at 17:37

1 Answers1

0

In the first variant, you define k locally inside the loop. That means it will really go out of scope and end its life-time every iteration of the loop. A pointer to that variable will become invalid each and every iteration as well as when the loop ends.

As for the reason all elements seems to be the same, it's because all elements are the same as all pointers in the stack will be to the single instance k. But as noted, these pointers (which are all the same) will immediately become invalid, and dereferencing them will lead to undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621