首页 > 解决方案 > 当结构非常简单时,malloc 是结构与整个结构的“成员”

问题描述

我在这个网站上搜索了malloc关于结构的主题。但是,我有一个小问题。malloc结构的元素是否与整个结构不同,malloc尤其是当该结构非常简单时,即只有一个我们都想要分配的成员?为了清楚起见,请参见下面与studentstudent2结构对应的代码。

struct student {
    int* majorScore;
};

struct student2 {
    int majorScore[3];
};


int main()
{
    struct student john;
    john.majorScore = (int*) malloc(sizeof(int) * 3);
    john.majorScore[0] = 50;
    john.majorScore[1] = 27;
    john.majorScore[2] = 56;
 
    struct student2* amy= (struct student2*)malloc(sizeof(struct student2));
    amy->majorScore[0] = 50;
    amy->majorScore[1] = 27;
    amy->majorScore[2] = 56;


    return 0;
}

它们的内存级别不同吗?如果是,有什么区别?如果不是,就良好的编程风格而言,哪个可能更好?

标签: cstructmemory-managementmalloc

解决方案


首先,您动态分配一个结构,而不是另一个。因此,您将苹果与橙子进行比较。


静态分配的结构:

struct student john;
john.majorScore = malloc(sizeof(int) * 3);
john.majorScore[0] = 50;
john.majorScore[1] = 27;
john.majorScore[2] = 56;

struct student2 amy;
amy.majorScore[0] = 50;
amy.majorScore[1] = 27;
amy.majorScore[2] = 56;
struct student john
+------------+----------+      +----------+
| majorScore |         ------->|       50 |
+------------+----------+      +----------+
| [padding]  |          |      |       27 |
+------------+----------+      +----------+
                               |       56 |
                               +----------+

struct student2 amy
+------------+----------+
| majorScore |       50 |
|            +----------+
|            |       27 |
|            +----------+
|            |       56 |
+------------+----------+
| [padding]  |          |
+------------+----------+

struct student使用更多内存,因为它有一个额外的值(指针),并且它有两个内存块而不是一个内存块的开销。

struct student2即使您需要更少的分数,也始终可以准确存储三个分数。而且它不可能容纳超过3个。


动态分配的结构:

struct student *john = malloc(sizeof(struct student));
john->majorScore = malloc(sizeof(int) * 3);
john->majorScore[0] = 50;
john->majorScore[1] = 27;
john->majorScore[2] = 56;

struct student2 *amy = malloc(sizeof(struct student2));
amy->majorScore[0] = 50;
amy->majorScore[1] = 27;
amy->majorScore[2] = 56;
struct student *john
+----------+      +------------+----------+      +----------+
|         ------->| majorScore |         ------->|       50 |
+----------+      +------------+----------+      +----------+
                  | [padding]  |          |      |       27 |
                  +------------+----------+      +----------+
                                                 |       56 |
                                                 +----------+

struct student2 *amy
+----------+      +------------+----------+
|         ------->| majorScore |       50 |
+----------+      |            +----------+
                  |            |       27 |
                  |            +----------+
                  |            |       56 |
                  +------------+----------+
                  | [padding]  |          |
                  +------------+----------+

分析同上。


推荐阅读