简体   繁体   English

动态分配的二维数组问题

[英]Dynamically allocated 2D Array issue

I am trying to understand what I am doing wrong when attempting to dynamically allocate the 2D array "allWordMultiArray" and assign values to it.我试图了解在尝试动态分配二维数组“allWordMultiArray”并为其分配值时我做错了什么。 I've been reading a lot of articles online (and in Stackoverflow in particular) and tried to implement it in a lot of ways but unsuccessfully.我一直在网上阅读很多文章(尤其是在 Stackoverflow 中)并尝试以多种方式实现它,但没有成功。 using C++ 14.使用 C++ 14。

So, the following code creates a warning of "Using uninitialized memory '*allWordMultiArray[i]'".因此,以下代码创建了“使用未初始化的内存 '*allWordMultiArray[i]'”的警告。 Obviously, when trying to cout the values in the 2D array it prints garbage.显然,当尝试计算 2D 数组中的值时,它会打印垃圾。 Can someone point to me what the problem is?有人可以指出我的问题是什么吗?

Here's a summary of the code:下面是代码的摘要:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

const int letters = 26;

int main() {
....

int numWords, pos;
string input;
int** allWordMultiArray;
cin >> numWords;

allWordMultiArray = new int* [numWords];

    for (int i = 0; i < numWords; i++) {
        cin >> input;

        allWordMultiArray[i] = new int[letters];
        for (unsigned long int j = 0; j < input.size(); j++)
        {
            pos = (input[j] - 'a');

            //Here is the problem. Garbage values
            allWordMultiArray[i][pos]++;
        }

    }
return 0;
}

Your help is very much appreciated.非常感激你的帮助。

This line:这一行:

allWordMultiArray[i] = new int[letters];

does allocate memory for an array, but the values in the array are indeterminate.确实为数组分配了内存,但数组中的值是不确定的。 Reading from these values, like here:从这些值中读取,例如:

allWordMultiArray[i][pos]++;

will invoke undefined behavior.将调用未定义的行为。

Just initialize the array when you allocate it:分配数组时只需初始化它:

allWordMultiArray[i] = new int[letters] {};
                                    //  ^^

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

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