[英]Dynamically allocate memory to an array in a separate function std::bad_alloc received
首先,我知道我可以使用std::vector
而不是arrays
,但我想使用數組,因為我想了解如何在聲明范圍之外分配內存。
我想將 common_words 數組傳遞給一個函數,並在該函數中分配一些內存。
當我運行我的代碼時,我收到了這個:
拋出“std::bad_alloc”實例后調用終止
what(): std::bad_alloc
這是代碼:
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
此外,我刪除了我之前說過的內容,以免它成為超長帖子,也因為它不相關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.