动态分配的C字符串数组

动态分配的C字符串数组

本文介绍了动态分配的C字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不清楚为什么会失败,以及为什么会失败:

I'm not clear why this should fail, and why it fails where it does:

std::string* s;
s = (std::string*)malloc(sizeof(std::string) * 10);
s[0] = "string0";
s[1] = "string1";
s[2] = "string2"; //Segmentation fault

分配给s [0]-s [2]的字符串的大小或malloc分配的空间都没有关系. QStrings也发生同样的事情.我认为麻烦来自于std :: string包含一个内部指针的事实,因此sizeof()仅返回指针的大小,但是鉴于std :: strings的行为类似于其他值(=,==等). )我不明白为什么这会导致失败.

It doesn't matter what the size of strings assigned to s[0] - s[2] are, or how much space is malloc'ed. The same thing happens with QStrings. I presume that the trouble arises from the fact that std::string contains an internal pointer, so sizeof() just returns the size of the pointer, but given that std::strings behave like values otherwise (=, ==, etc.) I don't see why that entails failure here.

此外,为了与其他代码兼容,我需要在这里使用C数组,而不是例如std :: vector.我正在寻找一种通用的解决方案(将与QString,QDateTime等配合使用).但是我很高兴知道发生了什么事.

Also, for compatibility with other code I need to use C arrays here, not e.g. std::vector. And I'm looking for a general solution (that will work with QString, QDateTime, etc) if there is one. But I'd be happy just to know what's going on.

得票了...这个问题怎么了?我确实先看了一眼(包括SO),没有找到解决的方法.

Got a downvote... What's wrong with this question? I did look around first for awhile (including SO), didn't find this addressed.

推荐答案

您不能malloc类对象的数组,因为此函数不会调用任何构造函数.您只会在内存中充满垃圾,然后尝试将其重新解释为类对象的数组.

You can not malloc an array of class objects, because this function does not invoke any constructors. You just get memory filled with garbage, which you then try to reinterpret as an array of class objects.

C ++对象的数组分配有new[].

Arrays of C++ objects are allocated with new[].

关于与其他代码的兼容性,您可能可以使用std::vector,因为&vec[0]为您提供了指向连续数组中第一个元素的指针.

As to compatibility with other code, you probably can use std::vector, because &vec[0] gives you a pointer to the first element in a contiguous array.

如果您坚持使用mallocfree,则需要为每个具有新放置位置的数组项手动调用构造函数,并在释放之前手动调用每个析构函数.

If you insist on using malloc and free, then you'll need to manually invoke the constructor for each array item with placement new and manually invoke each destructor before freeing.

这篇关于动态分配的C字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:15