V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
gejigeji
V2EX  ›  程序员

C 语言 静态数组

  •  
  •   gejigeji · 2014-07-25 20:35:01 +08:00 · 2730 次点击
    这是一个创建于 3555 天前的主题,其中的信息可能已经有所发展或是发生改变。
    为什么这么写也是合法的?

    #include <stdio.h>

    int main(){
    int n;
    scanf("%d", &n);
    char test[n];
    return 0;
    }

    在栈上分配内存不是应该要固定长度吗?

    Linux GCC
    7 条回复    2014-07-29 19:03:42 +08:00
    messense
        1
    messense  
       2014-07-25 20:40:41 +08:00
    bombless
        2
    bombless  
       2014-07-25 22:33:51 +08:00
    可变数组…等哪天你需要换vs编译就知错了…
    dorentus
        3
    dorentus  
       2014-07-25 22:42:07 +08:00
    ffffwh
        4
    ffffwh  
       2014-07-25 23:15:02 +08:00
    我在思考为什么原来(或VS中)不可以:
    比方说这样
    >>>>
    int a;
    int b[...];
    int c;
    <<<<
    变量的地址(即相对于栈指针的偏移)在编译时都应该是确定的。如果允许b长度不确定,那么就无法确定c的地址。

    我想问:
    请问是这么回事么?
    新实现(C99)里是如何实现可变数组的呢?
    paulw54jrn
        5
    paulw54jrn  
       2014-07-25 23:27:42 +08:00   ❤️ 2
    搬运工
    http://stackoverflow.com/questions/21182307/how-does-gcc-implement-variable-length-arrays

    Here's the allocation code (x86 - the x64 code is similar) for the following example line taken from some GCC docs for VLA support:

    char str[strlen (s1) + strlen (s2) + 1];
    where the calculation for strlen (s1) + strlen (s2) + 1 is in eax (GCC MinGW 4.8.1 - no optimizations):

    mov edx, eax
    sub edx, 1
    mov DWORD PTR [ebp-12], edx
    mov edx, 16
    sub edx, 1
    add eax, edx
    mov ecx, 16
    mov edx, 0
    div ecx
    imul eax, eax, 16
    call ___chkstk_ms
    sub esp, eax
    lea eax, [esp+8]
    add eax, 0
    mov DWORD PTR [ebp-16], eax
    So it looks to be essentially alloca().
    gejigeji
        6
    gejigeji  
    OP
       2014-07-29 18:54:11 +08:00
    @dorentus 可是我 gcc -std=c89 test.c 照样可以通过~
    gejigeji
        7
    gejigeji  
    OP
       2014-07-29 19:03:42 +08:00
    @dorentus 不管了 看别人代码里这么用的 我是不会这么用
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3496 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:08 · PVG 08:08 · LAX 17:08 · JFK 20:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.