简体   繁体   English

分配动态分配的指针数组

[英]Assigning dynamically allocated array of pointers

Having a lot of trouble with this after sifting through many posts on here. 在这里浏览许多帖子后,遇到了很多麻烦。 Everything compiles but I get a crash right here during this function which should be dynamically allocating the addresses of one array into this array of pointers. 一切都可以编译,但是在此函数执行期间我立即崩溃,该函数应该将一个数组的地址动态分配给该指针数组。 I see one or two memory addresses posted so I'm not sure why it would be crashing during the middle of this. 我看到发布了一个或两个内存地址,所以我不确定为什么在此过程中它会崩溃。

string *copyArray(string ptrArray[],int sizeArray)
   {
    string **dynamString = new string*[sizeArray];
    int i;

    for (i=0;i<=sizeArray;++i)
        {
         (*dynamString[i]) = ptrArray[i];
         cout << dynamString[i];
        }
    return *dynamString;

}

from main I have: 从主要我有:

string *arrPtr;

and the function call 和函数调用

arrPtr = copyArray(arrayOfStrings, arraySize);
for (i=0;i<=sizeArray;++i)

accesses an element behind the array yielding an undefined behavior . 访问数组后面的元素,产生未定义的行为 Elements are indexed from 0 to sizeArray - 1 . 元素的索引从0sizeArray - 1 Another problem is that you allocate the array of pointers: 另一个问题是您分配了指针数组:

string **dynamString = new string*[sizeArray];

and then you are derefencing these pointers although they do not point to any object yet: 然后您取消引用这些指针,尽管它们还没有指向任何对象:

(*dynamString[i]) = ptrArray[i];

which also causes an undefined behavior . 这也会导致不确定的行为 In case you wanted to create a deep copy, you should allocate the memory for every object as well: 如果要创建深层副本,则还应该为每个对象分配内存:

for (i = 0; i < sizeArray; ++i)
{
    dynamString[i] = new std::string(ptrArray[i]);
    cout << *dynamString[i];
}

However you should avoid using C-style arrays always when it is possible and prefer STL containers instead. 但是,应尽可能避免使用C型数组,而应首选STL容器。 In this case it could be neat std::vector<std::string> and its constructor that would do the same than your function (just in safer and more reasonable manner with no possible memory leaks): 在这种情况下,可能是整齐的std::vector<std::string>及其构造函数,其作用与您的函数相同(只是以更安全,更合理的方式进行,没有可能的内存泄漏):

std::vector<std::string> myStrings(arrayOfStrings, arrayOfStrings + arraySize);

ok I fixed it here. 好的,我在这里固定了。 My pointer syntax was incorrect. 我的指针语法不正确。 Here is the correct syntax. 这是正确的语法。

dynamString[i] = &ptrArray[i];

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

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