#include<iostream>
#include<cstdlib>
using
namespace std;
struct device
{
int num;
int count;
int reserve[0];//reserve是一个数组名;该数组没有元素;该数组的其实地址紧随结构题device之后;这种声明方法可以巧妙的实现C/C++语言里的数组扩展
};
int main()
{
struct device
*p_dev=(struct device*)malloc(sizeof(struct
device)+sizeof(int)*25);
//sizeof(int)*25是数组reserve的具体空间(25个元素)
p_dev->reserve[0]=99;
p_dev->reserve[24]=0;
cout<<"p_dev->reserve[0]="<<p_dev->reserve[0]<<endl;
cout<<"p_dev->reserve[24]="<<p_dev->reserve[24]<<endl;
cout<<"sizeof(struct device)="<<sizeof(struct
device)<<endl;
// 将结构体device之后的第一个内容(int值,其实就是reserve[0]的值)赋值给变量a
int a=*(&(p_dev->count)+1);
cout<<"a="<<a<<endl;
return
0;
}
本文介绍了一种使用 C++ 进行动态内存分配的方法,通过定义结构体并在运行时为其分配数组空间来实现。文章展示了如何为结构体的数组成员分配特定数量的元素,并演示了如何访问这些元素。
1487

被折叠的 条评论
为什么被折叠?



