开发者

Why have a 'static' definition in a function?

开发者 https://www.devze.com 2023-02-03 14:38 出处:网络
Considering the example at http://c-faq.com/misc/hexio.html, what is the reason to have an additional pointer t开发者_运维问答o a \'static\' character buffer? Why can\'t we get away with retbuf?Withou

Considering the example at http://c-faq.com/misc/hexio.html, what is the reason to have an additional pointer t开发者_运维问答o a 'static' character buffer? Why can't we get away with retbuf?


Without the static keyword, the buffer would be allocated on the stack -- and deallocated by the time the function returns to the caller.

Using static ensures the buffer is valid after the function returns.


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. E.g.:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消