简体   繁体   English

为什么在函数中有“静态”定义?

[英]Why have a 'static' definition in a function?

Considering the example at http://c-faq.com/misc/hexio.html , what is the reason to have an additional pointer to a 'static' character buffer? 考虑http://c-faq.com/misc/hexio.html上的示例,为什么有额外的指针指向“静态”字符缓冲区? Why can't we get away with retbuf ? 为什么我们不能摆脱retbuf

Without the static keyword, the buffer would be allocated on the stack -- and deallocated by the time the function returns to the caller. 如果没有static关键字,则缓冲区将在堆栈上分配-并在函数返回调用者时释放。

Using static ensures the buffer is valid after the function returns. 使用static确保函数返回后缓冲区有效。

You need a pointer so you can store a changing address. 您需要一个指针,以便可以存储更改的地址。 If you just had retbuf , you would have to design the function to use a changing index variable. 如果您只有retbuf ,则必须设计该函数以使用变化的索引变量。 Eg: 例如:

int ind = sizeof(retbuf)-1;
retbuf[ind] = '\0';

etc. 等等

Note that arrays are not pointers. 请注意,数组不是指针。 An array is a fixed-size region of memory. 数组是内存的固定大小区域。 A pointer is an address. 指针是地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM