前言
最近实验室的小伙伴们突然问我,在结构体内创建指针,如何开辟其内存大小,有种极其简单且易想到的方法,就是在外部对其malloc空间,但是本文可以给出两种比较优雅的实现方式。
1.利用构造结构体构造函数实现
跟类的实现方式十分接近,在构造函数里实现指定的指针开辟长度,代码很简单,且因为结构体成员共有的问题,在外部也可以对内存做释放。
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct number
{
number(int size)
{
temp = (int *)malloc(sizeof(int)*size);
}
int *temp;
};
int main()
{
const int length = 4;
number n(length);
for(int i = 0; i != length; i++)
{
n.temp[i] = i;
}
for(int i = 0; i != length; i++)
{
cout <<n.temp[i]<<endl;
}
free (n.temp);//可在结构体外部对结构体内指针做内存释放
system("pause");
}
代码执行结果如下:
在执行free后,其内存也可见被释放。
2.变长结构体
实验室另一位嵌入式大佬在书上所得,之前没见过,写出来看看眼。
struct number2//变长结构体的定义
{
int num;
int temp[];//此处定义必须放置在结构体定义的末尾
};
我们可以猜猜这个结构体为多少字节。
number2 n2;
cout << sizeof(n2) <<endl;
可见在对temp没有指定大小时,是不占用字节的。
具体使用时,要如何对这个不定长的数组定长呢?
#include <iostream>
#include <map>
#include <string>
using namespace std;
struct number1
{
number1(int size)
{
temp = (int *)malloc(sizeof(int)*size);
}
int *temp;
};
struct number2
{
int num;
int temp[];
};
int main()
{
const int length = 4;
number2 *n2 = (number2*)malloc(sizeof(int) * sizeof(length));//这里直接对变长结构体malloc
cout << sizeof(*n2) <<endl;//原结构体字节长度不变
for(int i = 0; i != length; i++)
{
n2->temp[i] = i;
}
for(int i = 0; i != length; i++)
{
cout <<n2->temp[i]<<endl;
}
free (n2->temp);//这里free无法在变量区查看是否free成功
system("pause");
}