简体   繁体   English

动态数组(GCC)和指针之间的区别

[英]Difference between dynamic arrays (GCC) and pointers

Considering following pieces of code: 考虑以下代码:

void foo() {
    int arraySize = getMyComputedValue();
    int dynamicArray[arraySize];

    fillDynamicArray(&dynamicArray[0]);

    for (int i = 0; i < arraySize; i++) {
        // Do something with data
    }
}

void bar() {
    int arraySize = getMyComputedValue();
    int* dynamicArray = new int[arraySize];

    fillDynamicArray(dynamicArray);

    for (int i = 0; i < arraySize; i++) {
        // Do something with data
    }

    delete[] dynamicArray;
    dynamicArray = NULL;
}

Both create a dynamic area in memory with varying lengths containing integers. 两者都在内存中创建一个动态区域,长度可变,包含整数。 I've found that the first example foo() (at least in my build environment) only compiles with GCC. 我发现第一个示例foo() (至少在我的构建环境中)仅使用GCC进行编译。

What are the exact differences between the two? 两者之间的确切区别是什么? Is the first example merely a GNU extension which is shorthand for the bottom example, allowing the compiler to determine when the correct time for de-allocation is? 第一个示例仅仅是GNU扩展,它是下一个示例的简写 ,允许编译器确定何时正确的解除分配时间? Or does the first example do exactly as the code says and allocates the memory on the stack? 还是第一个示例完全按照代码中的说明进行操作并在堆栈上分配内存?

  1. foo() allocates the memory on the stack, bar() allocates it on the heap. foo()在堆栈上分配内存, bar()在堆上分配内存。 This has two effects: Lifetime (stack memory is automatically reclaimed at function exit), and max array size (stack space is rather limited to a range of a few MB at most, heap space is only limited by available RAM). 这有两个影响:生命周期(函数退出时自动回收堆栈内存),以及最大数组大小(堆栈空间最多只能限制在几MB范围内,堆空间仅受可用RAM限制)。

  2. foo() is valid C99, but not C++ of any standard. foo()是有效的C99,但不是任何标准的C ++。 C++ simply never embraced VLAs. C ++根本就不接受VLA。 This is the core point where you need to realize that C and C++ are two quite distinct languages. 这是您需要意识到C和C ++是两种截然不同的语言的核心点。 There are valid C programs that are not C++ (like foo() ), and there are valid C++ programs that are not C (like bar() ). 有一些不是C ++的有效C程序(如foo() ),有一些不是C的有效C ++程序(如bar() )。 C++ is not the strict superset anymore as which it started. C ++从它开始时就不再是严格的超集。

Nevertheless, compilers may choose to implement a superset of the language as an extension. 但是,编译器可能选择将语言的超集实现为扩展。 g++ does so, but if you compile with strict C++ standard compliance ( g++ -std=c++14 -pedantic -Werror ), even g++ throws an error on foo() . g++ g++ -std=c++14 -pedantic -Werror ,但是如果您遵循严格的C ++标准合规性进行编译( g++ -std=c++14 -pedantic -Werror ),即使g++也会在foo()上引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM