-3

I just realized that in a while loop, when I create a pointer of a structure, the pointer seems undefined when the loop is over. I am not sure if there is such a thing as Pointers created in while loops cannot be used outside of it. Here is a part of my code:

if('D'==Status) //depature
{
    while(Top(T)->CarLicense != CarLin) {
        struct CarNode * tmp;
        tmp = Top(S);
        Push(TopAndPop(S), T);
        tmp->Movement++;
    }
    printf("Moved %d, bye!\n",tmp->Movement);
    DisposeCar(TopAndPop(T));
    while(!(IsEmpty(T))) {
        struct CarNode * tmp2;
        tmp2 = Top(T);
        Push(TopAndPop(T),S);
    }
}

Here, in printf("Moved %d, bye!\n",tmp->Movement);, tmp seems undefined.

Ashfaqur_Rahman
  • 140
  • 1
  • 9
Huzo
  • 1,652
  • 1
  • 21
  • 52
  • Possible duplicate of [Declaring variables inside loops, good practice or bad practice?](https://stackoverflow.com/questions/7959573/declaring-variables-inside-loops-good-practice-or-bad-practice) – Mark Benningfield Feb 27 '18 at 06:43
  • 1
    Utterly fundamental C: If you have a construct such as `{ int x; ... }` you cannot use `x` outside the braces. This is something you must realize before you even start to study pointers. – Lundin Feb 27 '18 at 09:04

1 Answers1

2

Because tmp is declared and defined in the while block it goes out of scope when the loop completes. You need to declare it in line above loop so it's still visible when it gets to the printf().

M. Ziegast
  • 165
  • 4
  • So, can we say that any variable declared in while loops only exist in the loop? – Huzo Feb 27 '18 at 06:23
  • 1
    To be safe, within any { } sub-block, yes... if you just declared auto variables without initializing them they can potentially see a previous value, but frequently it'll just be garbage that can cause seg faults and such. – M. Ziegast Feb 27 '18 at 06:34