开发者

In C, does an array of a structure gets allocated in the stack?

I think this maybe a really du开发者_C百科mb question, but i just want to be clarified. Thanks in advance! I'm not sure if an array of structure declared as a local variable inside a function gets allocated in the stack. Doesn't?


It does; anything you declare without allocating yourself (e.g. by calling malloc) or declare static (as Fernando says) is allocated on the stack. Structures are just a way of grouping together multiple variables; they still have a fixed size (the total size of their elements, possibly plus some padding), and accessing a struct's field just means pulling the appropriate bytes from somewhere within the struct


Unless you use malloc() (as @Michael Mrozek said) or declare it with the "static" modifier, it's allocated in the stack.


Yes, an array declared in a function scope as an auto variable will be allocated from the stack. You want to be judicious when doing so as you can never be certain from the calling context if there will be enough stack space to succeed. Even though Windows by default creates 1MB stacks for threads and Linux creates 8MB stacks by default, you can still have a problem if you create large arrays of structures. In some operating systems the thread stack may be as little as a few kB.

I tend to keep function scope auto variables limited to simple scalar types and put large abstract types and arrays on the heap.


It is just like other variable:

void function()
{

    struct my_struct a; // in the stack;
    struct my_struct *b = malloc(sizeof(struct my_strcut)); // not in the stack;
    static struct my_struct c; // not in the stack;

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜