我有几个关于为结构及其成员分配内存的问题。
假设我有这样一个结构:
struct _MyStruct
{
char *a;
}
typdef struct _MyStruct MyStruct;
我希望“a”是一个动态字符串,并且我想为其分配内存。在这种情况下,我是否也应该为 MyStruct 分配内存?示例:
MyStruct *myStr = malloc(sizeof(MyStruct)); //necessary? MyStruct *myStrCopy = myStr; myStrCopy->a=malloc(sizeof(char)); //checking for null//
现在假设我为结构 (
myStr
) 分配了 X 内存量。现在,当我将内存分配给 'a' 时,分配的内存是在分配给 myStr 的内存中分配的,还是它获得了一个新的内存块?我可以为“a”分配比分配给 myStr 的内存更多的内存吗?
假设我想用
realloc()
扩大'a'。我应该先放大myStr
吗?如果我这样做,那么需要多少内存(sizeof(myStr)*size_of_my_string)
?
最佳答案
- I want 'a' to be a dynamic string and I want to allocate memory to it. Should I allocate memory to MyStruct too in this case?
好吧,您的 MyStruct 始终需要存在,但有多种方法可以做到这一点,您应该选择适合您的用例的最简单的方法。
基本方法:
MyStruct myStr;
myStr.a = malloc(N); // "N chars please!"
// You can still get a pointer to this object:
foo(&myStr);
// Don't forget to free the `char` buffer later
free(myStr.a);
动态分配 — 有效,但不是必需的:
MyStruct* myStr = malloc(sizeof(MyStruct));
myStr->a = malloc(N); // "N chars please!"
// It's already a pointer, so:
foo(myStr);
// Don't forget to free the `char` buffer later
free(myStr->a);
// And then the struct
free(myStr);
- Now suppose I allocated an X amount of memory to the struct (myStr). Now, when I allocate memory to 'a', is the memory allocated within the memory allocated to myStr, or does it get a new block of memory?
这是一个新 block 。
每个动态分配的内存块都是完全独立的。当您使成员变量 a
成为指针时,您确保尽管 a
存在于结构中,但它指向的东西却不存在(除非您让它指向自身,哈哈)。
myStr (or *myStr): your malloc'd memory:
0 32 0 8 16 24 32 40 ...
+----------+ +------------------------------+
| char* a——|———————————————————————→| text or whatever here |
+----------+ +------------------------------+
(somewhere in memory) (somewhere else in memory)
无论您以何种方式构建myStr
,上图均有效。
- Can I allocate more memory to 'a' than I allocated to myStr?
是的,随心所欲。它是分开的。你有间接。
- Suppose I want to enlarge 'a' with realloc(). Should I enlarge myStr first? If I do, then by what amount of memory (sizeof(myStr)*size_of_my_string)?
没有。
关于c - 分配和重新分配结构及其元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31986454/