加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C中的动态内存分配?

发布时间:2020-12-16 10:07:31 所属栏目:百科 来源:网络整理
导读:为什么这样做? #include iostream int main() { std::cout "Enter a number: "; int arraySize; std::cin arraySize; int array[arraySize]; for(int element : array) { element = 42; std::cout element "n"; } std::cout "Array size: " sizeof(array)
为什么这样做?

#include <iostream>    

    int main()
    {
        std::cout << "Enter a number: ";
        int arraySize;
        std::cin >> arraySize;

        int array[arraySize];

        for(int element : array)
        {
            element = 42;
            std::cout << element << "n";
        }

        std::cout << "Array size: " << sizeof(array) << "n";
        std::cout << "Element count: " << sizeof(array)/sizeof(int);

        return 0;
    }

我对C中动态内存分配的理解告诉我,需要它的一种情况是你不知道在编译时需要分配的内存量.在这个程序中,显然编译程序时数组大小是未知的,但是是动态的,因为它可以随用户输入的值而改变.

以下是在成功编译(警告和无错误)后运行的程序:
g program.cpp -std = c 11 -o program.exe

输入一个数字:12
42
42
42
42
42
42
42
42
42
42
42
42
数组大小:48
元素数:12

如您所见,使用用户定义的元素数量创建了一个数组,
每个成功分配到42,并证明与sizeof()运算符一起存在.

为什么这不算作动态内存分配和编译?

解决方法

这个可变长度数组(VLA)的声明不是标准的:

int array[arraySize];

此行与g编译的原因是编译器已将此功能提供为extension:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读