Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在单独的函数std::bad_alloc received中将内存动态分配给数组_C++_Arrays_Dynamic Memory Allocation - Fatal编程技术网

C++ 在单独的函数std::bad_alloc received中将内存动态分配给数组

C++ 在单独的函数std::bad_alloc received中将内存动态分配给数组,c++,arrays,dynamic-memory-allocation,C++,Arrays,Dynamic Memory Allocation,首先,我知道我可以使用std::vector而不是数组,但我想使用数组,因为我想了解如何在声明范围之外分配内存 我想将公共_单词数组传递给一个函数,并在该函数中分配一些内存 当我运行代码时,我收到以下信息: 在抛出“std::bad_alloc”实例后调用terminate 什么:性病::坏的 代码如下: void allocSpace(std::string *&common_words, int words_k) { common_words = new std::stri

首先,我知道我可以使用std::vector而不是数组,但我想使用数组,因为我想了解如何在声明范围之外分配内存

我想将公共_单词数组传递给一个函数,并在该函数中分配一些内存

当我运行代码时,我收到以下信息:

在抛出“std::bad_alloc”实例后调用terminate 什么:性病::坏的

代码如下:

void allocSpace(std::string *&common_words, int words_k)
{
     common_words = new std::string[words_k];   
}

int main(void)
{
    int words_k = 0, comma_k = 0;
    std::string *common_words;

    std::cout << "Enter the words to be ignored separated by \',\': " << std::endl;
    std::getline(std::cin, words_list);

    comma_k = getCommaNumber(words_list); // returns 2 (const int value)
    words_k = comma_k + 1;

    allocSpace(common_words, words_k);

    return 0;
}

谢谢大家!

编辑。。。。下面是一个例子和一幅图片,展示了记忆中正在发生的事情

int* allocateArray(int size){
    int *ptrArray = new int[size];
    return ptrArray;
所以一行一行。定义数组并放入其参数。为此,我们将得到数组的大小。int size接下来我们需要创建内存位置并给它一个指针。int*ptrArray=new int[size]接下来,我们要返回指针的值,因此它所指向的地址也基本相同。return ptrArray注意,当我们定义数组时,我们如何执行int*以让它知道我们将返回指针的值。这是一个超级简单的img,它在内存中的样子


另外,我删除了我之前说过的内容,不让它成为一篇超长文章,也因为它不相关。

你确定单词的价值吗?如果您在调用allocSpace之前打印它,您会得到什么?简单地使用std::vector怎么样?但是,当您调用新的std::string[words_k]时,words_k的值是多少?这可能就是你失败的原因。@NathanOliver我收到1878006339:。你是对的,问题出在getCommaNumber函数中。看起来你需要调试getCommaNumber。请感谢你的回答,但对我来说,重要的是要理解如何在外部函数中为一个数组动态分配内存。另外请注意:我知道内存表是一个非常糟糕/简化的示例,但它很重要你的大脑如何思考这些事情。