C++ 初始化全局数组

标签 c++ arrays

大家好。我是一名经验丰富的 Java 程序员,正在学习 C++。

现在我有一点初学者的问题。我有一个 int 类型的数组变量 x。

用户会在方法B中输入x的大小,我想在方法A中使用x。

void method A()
{
 using int x [] blah blah blah
}

void method B()
{
int n;
cin >>n;
int x [n]; // How can I use this int x in method A without getting error: storage size x is unknown.
// Or the error 'x' was not declared in this scope.
}

编辑:参数传递不是我正在寻找的解决方案。

双重编辑:我确实知道 vector 选项,但我的程序正在按时补习。我正在创建一种每一毫秒都很重要的算法。

顺便说一句,我找到了一种方法。

int x [] = {}

method B();
method A () { blah blah use x}
method B () {/*int*/ x [n]}

最佳答案

如果您实际上想要一个数组而不是一个 vector ,并且您希望该数组在运行时动态调整大小,您需要在堆上创建它(将它存储在一个指针中),并在完成后释放它。

来自 Java,您需要了解 C++ 中没有垃圾收集 - 您在对象中新建(在堆上创建)的任何内容都需要在析构函数中使用 进行清理删除

class foo
{
    private:
    int *array;

    public:
    foo() { array = NULL; };
    ~foo()
    {
        if (array != NULL)
            delete [] array;
    }

    void createArray()
    {
        array = new int[5];
    }

};

更多信息请访问:http://www.cplusplus.com/doc/tutorial/dynamic/

关于C++ 初始化全局数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5914992/

相关文章:

c++ - 为什么我的 or 语句不起作用,C++?

c++ - 仅打印 QPlainTextEdit 文档纯文本

c++ - 从 "dumb"基类构造对象

c++ - 在 C++ 中,如何将 ASCII 艺术打印到控制台?

c++ - 交叉编译: special cross compiler or just gcc with option -march?

PHP:array_search 返回 null

php - 使用数组的数字键从数据库中存储多维数组

javascript - 单击按钮不会更新我的 React 应用程序中的状态

Java纸牌游戏: Deck Class help needed

c# - 无法使用 whis json 反序列化当前 JSON 对象