struct char[0] 零长数组使用

本文探讨了C语言中变长数组的限制,如不能返回变长数组的指针、增加栈溢出风险,并列举了若干不可用场景。然而,GCC允许在结构体中使用零长数组,作为一种特殊技巧,特别是在动态字符串处理和共享内存配置大小时。通过示例展示了如何在Str结构体中利用零长数组实现动态字符串功能。

在c中虽然支持了变长数组,但是在使用的时候还是会有诸多限制。比如分配在栈上,也就是说不能返回变长数组的指针,同时还增加了栈溢出的风险,以下是几种不能使用的场景。

  1. 不能使用extern声明的长度
  2. 在struct members中定义长度
  3. 在static变量中定义长度
  4. 在函数定义中定义长度
extern int n;
int A[n];                           // invalid: file scope VLA
extern int (*p2)[n];                // invalid: file scope VM
int B[100];                         // valid: file scope but not VM
void fvla(int m, int C[m][m]);      // valid: VLA with prototype scope
void fvla(int m, int C[m][m])       // valid: adjusted to auto pointer to VLA
{
    typedef int VLA[m][m];          // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];                // invalid: y not ordinary identifier
        int z[n];                   // invalid: z not ordinary identifier
    };
    int D[m];                       // valid: auto VLA
    static int E[m];                // invalid: static block scope VLA
    extern int F[m];                // invalid: F has linkage and is VLA
    int (*s)[m];                    // valid: auto pointer to VLA
    extern int (*r)[m];             // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;        // valid: q is a static block pointer to VLA
    }

好在GCC 中允许使用零长数组,把它作为结构体的最后一个元素时可以实现一些特别的功能,比如我最近想在共享内存上通过参数来动态配置大小,就使用了这种技术。我们来看一个动态字符串的例子。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

typedef struct _str {
  int len;
  char data[0];
} Str;

int main()
{
  char *test = "this is a test";
  int len = strlen(test);
  printf("test=%s len=%d\n", test, len);
  Str *str = (Str*)malloc(sizeof(Str) + len * sizeof(char));
  strcpy(str->data, test);
  str->len = len;
  printf("s=%s,len=%d\n", str->data, str->len);
  return 0;
}

通过上述例子我们可以看出Str结构体中的data成功的指向了字符串的首地址,也没有非法访问的错误。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值