与基于C的malloc字符串数组++ [英] Array of strings with malloc on C++

查看:188
本文介绍了与基于C的malloc字符串数组++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关的,我没有控制的原因列表,我需要创建一个字符串数组,需要从一个void *指针引用。我们的想法是按照C ++以下模式:

 无效* TP =的malloc(sizeof的(双)* SS);
的for(int i = 0; I< SS,我++){
  ((双*)TP)[I] = IStringToDouble(令牌[I]);
}

当令牌是一个向量和SS一个int。现在,使用该模板,我虽然开始是这样的:

 无效* TP =的malloc(sizeof的(字符串)* SS);
的for(int i = 0; I< SS,我++){
  ((字符串*)TP)[我] =令牌[I]
}

我知道,这是可怕的错误,但所有的修改,我试图从开始就不起作用。

有关如何实现这一目标的任何建议吗?这可能吗?

我已经经历了所有关于我从谷歌或计算器发现C字符串数组++的文档了,但他们都不占地约从虚空引用数组的问题*。


解决方案

 无效* TP =的malloc(sizeof的(字符串)* SS);
的for(int i = 0; I< SS,我++){
  ((字符串*)TP)[我] =令牌[I]
}

这是可怕的,但我会忽略,并解释为什么它打破,如何得到它的工作....

的malloc()分配内存,但它并没有建造任何对象。对于字符串,你需要调用构造函数 - 否则新的字符串实例将包含未初始化的指针成员,字符串对象将承担的内存指针实际文本数据:((字符串*)TP)[我] =令牌[I]; 将尽量保证容量和覆盖内存基于这些垃圾值。

要解决此问题,使用位置,新的运营商来构造每个串的:

 无效* TP =的malloc(sizeof的(字符串)* SS);
的for(int i = 0; I< SS,我++){
  新的(及((字符串*),TP)[I])的std ::串(令牌[I]);
}

您将需要销毁字符串取值之后同样通过调用析构函数明确,然后免费()阵列。

For a list of reasons that I do not control, I need to create an array of strings that needs to be referenced from a void* pointer. The idea is to follow the following pattern in C++:

void* TP = malloc(sizeof (double) * SS);
for (int i = 0; i < SS; i++) {
  ((double*) TP)[i] = IStringToDouble(Token[i]);
}

Where Token is a vector and SS an int. Now, using that template, I though starting with something like:

void* TP = malloc(sizeof (string) * SS);
for (int i = 0; i < SS; i++) {
  ((string*) TP)[i] = Token[i];
}

I know that this is horribly wrong, but all the modifications I have tried starting from it don't work.

Any suggestion about how to achieve this? Is it possible?

I have gone through all the documentation about string arrays on C++ that I have found from Google or StackOverflow, but none of them covers the issue about referencing the array from a void*.

解决方案

void* TP = malloc(sizeof (string) * SS);
for (int i = 0; i < SS; i++) {
  ((string*) TP)[i] = Token[i];
}

This is horrible, but I'll ignore that and explain why it's broken and how to get it working....

malloc() allocates memory but doesn't construct any objects in it. For string, you need to invoke the constructor - otherwise the new string instances will contain uninitialised pointer members that the string object will assume are pointers to memory for the actual text data: ((string*) TP)[i] = Token[i]; will then try to ensure capacity and overwrite memory based on these garbage values.

To fix this, use the placement-new operator to construct each of the strings:

void* TP = malloc(sizeof (string) * SS);
for (int i = 0; i < SS; i++) {
  new (&((string*)TP)[i]) std::string(Token[i]);
}

You'll need to destroy the strings similarly afterwards by calling their destructors explicitly, and then free() the array.

这篇关于与基于C的malloc字符串数组++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆