V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
danny106
V2EX  ›  问与答

C 语法求介绍

  •  
  •   danny106 · 2014-05-16 16:40:18 +08:00 · 2611 次点击
    这是一个创建于 3641 天前的主题,其中的信息可能已经有所发展或是发生改变。
    本来:
    印象当中是不能这样写的:
    int iVar = 5;
    char *content[iVar];
    应该:
    int iVar = 5;
    char **content = (char**)malloc(sizeof(char*)*iVar);
    但是:
    我已经发现好几个开源代码都是直接 char *content[iVar];
    到底是个什么情况,求解释
    13 条回复    2014-05-16 18:36:35 +08:00
    leavic
        1
    leavic  
       2014-05-16 16:48:12 +08:00
    你printf看一下content的长度
    leavic
        2
    leavic  
       2014-05-16 16:50:25 +08:00
    我感觉content是一个指向指针的指针,而不是一个数组,所以不需要分配空间.
    aszxqw
        3
    aszxqw  
       2014-05-16 16:50:38 +08:00
    编译器在作怪。
    jkneedout
        4
    jkneedout  
       2014-05-16 16:53:50 +08:00
    #define iVar 5
    顺便贴下你看到的开源代码地址吧
    leavic
        5
    leavic  
       2014-05-16 16:55:47 +08:00
    啊,我想起来了,这种用法我也写过,我是直接char Buff[200],不需要Malloc.
    直接写char *content[iVar]是可以自动分配空间的,但在这个函数结束之后,这部分内存会被回收,而且你无法在定义他的函数之外访问它,malloc的意义是建立一个可以被公共访问的指针,如果你只在一个函数内使用这个数组,用完就不管,是可以不用malloc的.
    而且,有些时候其实你没法控制这个数组的消亡时间,不知道在什么地方去free他,用malloc反而会造成内存无法回收.
    leavic
        6
    leavic  
       2014-05-16 16:57:14 +08:00
    至于建立数组的时候,长度不能是变量只能是常量的问题,我只能说是编译器的问题,有些编译器现在真的可以支持变量做长度.
    mulog
        7
    mulog  
       2014-05-16 16:58:31 +08:00
    C99

    https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

    Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits
    LMkillme
        8
    LMkillme  
       2014-05-16 17:02:23 +08:00
    可以这样写,C99支持的,初始化时就决定数组大小了,之后你改变ival的值也不行。
    LMkillme
        9
    LMkillme  
       2014-05-16 17:02:52 +08:00   ❤️ 1
    gcc支持,g++不支持
    chchwy
        10
    chchwy  
       2014-05-16 17:39:19 +08:00
    C99最新的標準, 另外這是C跟C++不相容的地方。
    danny106
        11
    danny106  
    OP
       2014-05-16 17:40:35 +08:00
    ChiangDi
        12
    ChiangDi  
       2014-05-16 17:55:35 +08:00
    VLA,好像叫变长数组。
    sandtears
        13
    sandtears  
       2014-05-16 18:36:35 +08:00
    这不就是 C99 标准么,C99 允许直接用变量定义数组长度。

    如果你用的 gcc, 那么编译的时候指明 `-std=c99` 就行了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2494 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 12:20 · PVG 20:20 · LAX 05:20 · JFK 08:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.