Reputation: 25
I am writing a function which is meant to be called multiple times, where I want to have a static pointer to the beginning of a list. I need the function, no matter how many times it is called, to access the same list, so I have two questions.
Am I right that if I declare it static t_line *begin = NULL;
where t_line
is my struct, I believe it will already have allocated the correct space before main()
is called, as I understand static
variables do, then this will give me a null pointer with the correct allocated size.
Once I give that static pointer the address of the first element in my list, the next time the function is called and it reaches that declaration line, wouldn't it just reset it to NULL
and I'd lose my pointer?
Upvotes: 2
Views: 774
Reputation: 134366
Variables with static
storage are initialized only once, you're good to go.
Quoting C11
, chapter §6.2.4, emphasis mine
An object whose identifier is declared without the storage-class specifier
_Thread_local
, and either with external or internal linkage or with the storage-class specifierstatic
, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
That said, regarding retaining the last-stored value, quoting paragraph 2, (again, my emphasis)
The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime.34) [....]
and, for static
variables, as mentioned above
Its lifetime is the entire execution of the program
Upvotes: 1