zoukankan      html  css  js  c++  java
  • 0长数组介绍

    0长数组介绍:也叫柔性数组

    用途:为了满足需要变长度的结构体

    用法:在一个结构体的最后,申明一个长度为0的数组,就可以实现这个结构体长度的可变,如:

    typedef struct _Student

    {

      int Age;

      int Length;

      char Info[0];//0长数组

    }Student,*pStudent;

    说明:

    1、长度为0的数组并不占用空间,sizeof(Student)=8。

    2、它只是一个偏移量,数组名这个符号本身代表了一个不可修改的地址常量。

    优缺点:

    优点:比起在结构体中声明一个指针变量,再进行动态分配的办法,这种方法效率要高,因为在访问数组内容时,不需要间接访问,避免了两次访存。

    缺点:在结构体中,为0的数组必须在最后声明,使用上有一定限制。

    例子:

    #include <QApplication>

    #include <QDebug>

    #include <QString>

    int main(int argc,char* argv[])

    {

      //局部变量

      int age = 10;

      QString name = "张三";

      //创建并初始化

      Student* student = (Student*)malloc(sizeof(Student) + name.length());

      student->Age = age;

      student->Length = name.length();

      memcpy(student->Info,name.toLocalBit8().data(),name.length());

      //打印

      qDebug()<<stutent->Age<<student->Info;

      //释放(一次释放即可)

      free(student);

      student = NULL;

    }

  • 相关阅读:
    curl 命令行使用参考
    PHP 输出json_encode 空白的检查
    RAM和ROM
    浮点数
    负数补码
    位运算
    无法加载文件 C:UsershuangshiminAppDataRoaming pmwechat-terminal.ps1,因为在此系统上禁止运行脚本
    windows + php + shell_exec 执行失败的可能原因
    Ubuntu 发送邮件
    红黑树
  • 原文地址:https://www.cnblogs.com/zhangnianyong/p/12199964.html
Copyright © 2011-2022 走看看