在不使用动态内存分配的情况下声明可变大小的数组 [英] Declaring variable sized array without using dynamic memory allocation

查看:50
本文介绍了在不使用动态内存分配的情况下声明可变大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在函数中分配可变大小的2D数组而不使用新的运算符,以便该2D数组可用于同一文件中的其他函数.

I want to allocate variable sized 2D array in a function without using new operator such that this 2D array is available to other functions in the same file.

    void draw(int i)
    {   size=i;   }

    void assign(char symbol)
    {
        char one[size][size];
        /// ... Assigning values to one  ...
    }
    void display()
    {   /// Displaying values of one[size][size]
        for(int i=0;i<size;i++)
        {
            for(int j=0;j<size;j++)
            cout<<one[i][j];
            cout<<endl;
        }
    }

函数的执行顺序为绘制->分配->显示

Execution order of functions is draw -> assign -> display

可能早些时候曾问过这个问题.但是我的问题是->我无法在全局分配函数之外声明数组,因为不知道size的值.->我无法在显示"功能中使用一个"数组,因为其范围仅限于分配"功能.

This question may have been asked earlier. But my problem is.. -> I can't declare the array outside assign function globally because value of size is not known. -> I can't use "one" array in "display" function because its scope is limited to "assign" function.

我也不想使用new或malloc运算符.如果有其他选择,请帮助.

And I also don't want to use either new or malloc operators. Please help if there is any alternative available.

推荐答案

C ++不支持像C99这样的堆栈分配的可变长度数组.您应该改为使用 std :: vector< T> .如果您确实要使用堆栈分配,则可以使用 alloca().

C++ doesn't support stack-allocated Variable Length Arrays like for example C99. You should use std::vector<T> instead. If you really want to use stack allocation you can use alloca().

这篇关于在不使用动态内存分配的情况下声明可变大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆