0

I've been trying to wrap my head around static variables in C and so I wrote this:

#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int *pointer;
void stat();

int main()
{
    stat(); 
    printf("%i", *pointer);
}

void stat()
{
    int c = 2;
    pointer = &c;
}

This does work and display 2 in the command line, but I don't understand why. Doesn't int c cease to exist when the function stat exits? Then what does pointer point to? And how does it retain the value of the integer? Why can I do without making int c static here?

user3614293
  • 385
  • 5
  • 13
  • 3
    `c` ceases to exist, but that doesn't mean the memory space stops holding the value that `c` contained. But you can't garantee that this will always be the case. `pointer` points to that space in memory. – AntonH Jun 24 '14 at 00:29

2 Answers2

1

c ceases to exist, but you're still allowed to look at that memory location, and you're getting lucky; the value is still there at that moment-- it hasn't been overwritten by anything else yet.

Your understanding is correct; pointer is pointing at memory you shouldn't be looking at once stat returns.

Ben Zotto
  • 70,108
  • 23
  • 141
  • 204
1

c as an object ceases to exist. But your pointer does not cease to exist because it is global. Your pointer is pointing to the memory address where c was. It will continue pointing there unless you poi it somewhere else. But, the content at that address could change if something else is assigned that address or overlaps that in memory later.

I should add that nothing here is a static anything. The static keyword has special significance and it has a deferent effect depending on the scope in which it is declared.

uchuugaka
  • 12,679
  • 6
  • 37
  • 55