C语言中变长数组--struct hack

2020-03-27  本文已影响0人  心理健康最重要

struct hack 是一种用来实现变长数组的常见技巧,不必再构造时就确定数组的长度,延迟到运行时确定。

c标准中的描述

As a special case, the last element of a structure with more than one named member may
have an incomplete array type; this is called a flexible array member.

c99standard

c89:通过struct hack 实现变长数组

struct DynamicStr{
          int length;
          int free;
          char str[0];
};
char* DynamicStrNew(const void* init_str,size_t init_len){
          struct DynamicStr*  p;
          if(init_str&&init_len>=0)
                p = (struct DynamicStr*)malloc(sizeof(struct DynamicStr)+len+1);
         else
                return NULL;
         if(!p)  return NULL;
         p->length = len;
         p->free =  0;
         memcpy(p->str,init_str,init_len);
         p->str[init_len]  = '\0';
         return p->str;
}

DynamicStr结构体的大小在32bit下位8字节;

在c99中引入了variable-length array(VLA)

int n;
scanf("%d",&n);
char str[n];
上一篇下一篇

猜你喜欢

热点阅读