0 长数组

#include <stdio.h>
#include
<string.h>
#include
<stdlib.h>
struct aa{
   
int a;
   
int b;
};

struct bb{
   
struct aa test[0];
};

int main(void)
{
   
struct bb *p=(struct bb*)malloc(sizeof(struct bb)+sizeof(struct aa)*100);
    p
->test[0].a=10;
    p
->test[0].b=20;
    printf(
"%d,%d\n",p->test[0].a,p->test[0].b);
   
return 0;
}

 

 

 

 

看这个结构体的定义:

 


 
 
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> typedef struct st_type { int nCnt; int item[ 0 ]; }type_a;

 

(有些编译器会报错无法编译可以改成:)

 


 
 
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> typedef struct st_type { int nCnt; int item[]; }type_a;

 


    这样我们就可以定义一个可变长的结构,用sizeof(type_a)得到的只有4,就是sizeof(nCnt)=sizeof(int)那个0个元素的数组没有占用空间,而后我们可以进行变长操作了。

 

 

 


 
 
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> // C语言版: type_a * p = (type_a * )malloc( sizeof (type_a) + 100 * sizeof ( int )); // C++语言版: type_a * p = (type_a * ) new char [ sizeof (type_a) + 100 * sizeof ( int )];

 

 

 

 

 

    这样我们就产生了一个长为100的type_a类型的东西用p->item[n]就能简单地访问可变长元素,原理十分简单,分配了比sizeof (type_a)多的内存后int item[];就有了其意义了,它指向的是int nCnt;后面的内容,是没有内存需要的,而在分配时多分配的内存就可以由其来操控,是个十分好用的技巧。
而释放同样简单:

 

 

 


 
 
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> // C语言版: free(p); // C++语言版: delete []p;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值