c - 当结构非常简单时,malloc 是结构与整个结构的“成员”
问题描述
我在这个网站上搜索了malloc
关于结构的主题。但是,我有一个小问题。malloc
结构的元素是否与整个结构不同,malloc
尤其是当该结构非常简单时,即只有一个我们都想要分配的成员?为了清楚起见,请参见下面与student
和student2
结构对应的代码。
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;
}
它们的内存级别不同吗?如果是,有什么区别?如果不是,就良好的编程风格而言,哪个可能更好?
解决方案
首先,您动态分配一个结构,而不是另一个。因此,您将苹果与橙子进行比较。
静态分配的结构:
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] | |
+------------+----------+
分析同上。
推荐阅读
- polymer - 在测试聚合物时无法读取未定义的属性“匹配”
- reactjs - 我们如何在 React 应用程序中配置适用于本地和生产环境的服务器 URL?
- sql - SQL Server - 过去 52 周到给定周的交易量的分配(总和)
- angular - 如何引用数组中的组件?
- java - 一个简单的问题,关于动态 Java,它可行吗?还是完全不可能?
- javascript - Javascript:计算两个日期之间的月数
- python - 尝试用 IronPython 做线性代数
- javascript - jQuery DataTables:隐藏搜索栏
- php - PHP SoapClient WSDL 请求参数结构
- php - Wordpress 搜索栏结果为空白白页