更换的realloc(C - > C ++) [英] Replacing realloc (C --> C++)

查看:150
本文介绍了更换的realloc(C - > C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在前面一个问题,我问了一下类型转换三分球,但被定向到使用C ++分配制度,而不是mallocs的更好的解决方案。 (我把一些C code到C ++)

In an earlier question, I asked about typecasting pointers, but was directed to the better solution of using the C++ allocation system instead of mallocs. (I am converting some C code to C++)

不过,我仍然有一个问题有类似的功能:

However, I still have an issue with a similar function:

我改了:

tmp = malloc(sizeof(char*) * mtmp); --> tmp = new char*[mtmp];

free(tmp) --> delete [] tmp;

然而,办在下面的函数realloc的是什么:

However, what do I do with realloc in the following function:

char* space_getRndPlanet (void)
{
   int i,j;
   char **tmp;
   int ntmp;
   int mtmp;
   char *res;

   ntmp = 0;
   mtmp = CHUNK_SIZE;
   //tmp = malloc(sizeof(char*) * mtmp); <-- replaced with line below
   tmp = new char*[mtmp];
   for (i=0; i<systems_nstack; i++)
      for (j=0; j<systems_stack[i].nplanets; j++) {
         if(systems_stack[i].planets[j]->real == ASSET_REAL) {
            ntmp++;
            if (ntmp > mtmp) { /* need more space */
               mtmp += CHUNK_SIZE;
               tmp = realloc(tmp, sizeof(char*) * mtmp); <--- Realloc
            }
            tmp[ntmp-1] = systems_stack[i].planets[j]->name;

我收到以下错误:

I am getting the following error:

error: invalid conversion from 'void*' to 'char**'|

编辑2:

好吧,我得到的共识是,我应该抛弃我目前的解决方案(我愿意接受这样做)。

Okay, the consensus I am getting is that I should ditch my current solution (which I am open to doing).

只是为了确保我理解正确的话,做你们的意思是说,而不是指向对象的数组,我应该有一个包含对象本身的载体?

推荐答案

C允许无效* 隐式转换为任何指针。 C ++没有,所以如果你使用的realloc ,你要的结果转换为适当的类型。

C allows void* to be implicitly converted to any pointer. C++ doesn't, so if you're using realloc, you have to cast the result to the appropriate type.

但更重要的是,使用的realloc 返回一个指向新的[] 是未定义的行为。而且也没有直接的C ++ - 相当于风格的realloc

But more importantly, using realloc on a pointer returned by new[] is undefined behavior. And there's no direct C++-style equivalent to realloc.

您的选择是,从最低到最高习惯:

Your choices are, from least to most idiomatic:


  • 棒到的malloc / 的realloc / 免费和投指针。

  • 使用新[] + 删除[] 而不是的realloc

  • 使用的std ::矢量&lt;标准::字符串&GT; ,而不是管理自己的存储

  • Stick to malloc/realloc/free and cast the pointers.
  • Use new[] + delete[] instead of realloc
  • Use std::vector<std::string> instead of managing your own memory.

这篇关于更换的realloc(C - &GT; C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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