开发者

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 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜