c - 分配和重新分配结构及其元素

标签 c pointers memory-management struct dynamic-memory-allocation

我有几个关于为结构及其成员分配内存的问题。

假设我有这样一个结构:

struct _MyStruct
{
    char *a;
}
typdef struct _MyStruct MyStruct;
  1. 我希望“a”是一个动态字符串,并且我想为其分配内存。在这种情况下,我是否也应该为 MyStruct 分配内存?示例:

    MyStruct *myStr = malloc(sizeof(MyStruct)); //necessary?
    MyStruct *myStrCopy = myStr;
    myStrCopy->a=malloc(sizeof(char));
    //checking for null//
    
  2. 现在假设我为结构 (myStr) 分配了 X 内存量。现在,当我将内存分配给 'a' 时,分配的内存是在分配给 myStr 的内存中分配的,还是它获得了一个新的内存块?

  3. 我可以为“a”分配比分配给 myStr 的内存更多的内存吗?

  4. 假设我想用realloc() 扩大'a'。我应该先放大 myStr 吗?如果我这样做,那么需要多少内存 (sizeof(myStr)*size_of_my_string)

最佳答案

  1. 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);
  1. 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,上图均有效。

  1. Can I allocate more memory to 'a' than I allocated to myStr?

是的,随心所欲。它是分开的。你有间接

  1. 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/

相关文章:

c - 未定义数组的默认地址是否始终是有效地址?

c - 如何在C中返回指向数组的指针?

memory-management - 进程地址空间和虚拟内存

c++ - imread 命令后 OpenCV 矩阵内存释放

c - 将十六进制格式的整数数组保存到 char "string"

c - 使用 strtok 函数后将数组位置分配给夹板字

c - 如何提高使用 void** 实现的动态数组的性能?

我可以更快地在整数之间传输符号(在 C5515 上)吗?

c - 在 C 中将数组作为参数传递

c - 你如何管理 C 中结构的内存?