gpt4 book ai didi

c - 重复调用的函数中的静态变量 C

转载 作者:太空宇宙 更新时间:2023-11-03 23:42:48 25 4
gpt4 key购买 nike

我正在编写一个要被多次调用的函数,我想在其中有一个指向列表开头的静态指针。无论调用多少次,我都需要该函数来访问同一个列表,所以我有两个问题。

  1. 我是否正确,如果我声明它 static t_line *begin = NULL; 其中 t_line 是我的结构,我相信它已经分配了正确的调用 main() 之前的空间,据我所知,static 变量所做的,然后这将给我一个具有正确分配大小的空指针。

  2. 一旦我为该静态指针提供列表中第一个元素的地址,下次调用该函数并到达该声明行时,它不会只是将其重置为 NULL,我会丢失我的指针吗?

最佳答案

具有static 存储的变量仅初始化一次,您可以开始了。

引用 C11,第 6.2.4 章,强调我的

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 specifier static, 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.

也就是说,关于保留最后存储的值,引用第 2 段,(再次强调)

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) [....]

并且,对于 static 变量,如上所述

Its lifetime is the entire execution of the program

关于c - 重复调用的函数中的静态变量 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41015280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com