c++ - 数组作为 C++ 中的输出参数

标签 c++ arrays pass-by-pointer

我创建了一个返回错误代码(ErrCode 枚举)并传递两个输出参数的函数。但是当我打印函数的结果时,我没有在数组中得到正确的值。

// .. some codes here ..
ErrCode err;
short lstCnt;
short lstArr[] = {};
err = getTrimmedList(lstArr, &lstCnt);

// list returned array (for comparison)
for (int i=0; i<lstCnt; ++i)
 printf("lstArr[%3d] = %d", i, lstArr[i]);
// .. some codes here ..

getTrimmedList 函数是这样的:

ErrCode getTrimmedList(short* vList, short* vCnt)
{
  short cnt;
  ErrCode err = foo.getListCount(FOO_TYPE_1, &cnt);
  if (NoError!=err) return err;

  short* list = new short [cnt];

  short total = 0;
  for (short i=0; i<cnt; ++i)
  {
    FooBar bar = foo.getEntryByIndex(FOO_TYPE_1, i);

    if (bar.isDeleted) continue;

    list[total] = i;
    ++total;
  }

  *vCnt = total;
  //vList = (short*)realloc(index, sizeof(short)*total);
  vList = (short*)malloc(sizeof(short)*total);
  memcpy(vList, list, sizeof(short)*total)

  // list returned array (for comparison)
  for (int i=0; i<lstCnt; ++i)
   printf("lstArr[%3d] = %d", i, lstArr[i]);

  return NoError;
}

哪里:

  • foo 是一个包含 FooBar 对象数组的对象
  • foo.getListCount() 返回类型为 FOO_TYPE_1 的对象数
  • FOO_TYPE_1 是我们想要获取/列出的对象类型
  • foo.getEntryByIndex() 返回类型为 FOO_TYPE_1 的第 iFooBar 对象
  • bar.isDeleted 是一个标志,指示 bar 是否被视为“已删除”

我的错误是什么?

编辑:

对不起,我抄错了一行。我在上面对其进行了评论并放置了正确的行。

编辑2

我无法控制 foobar 的返回值。它们的所有函数返回都是 ErrCode 并且输出通过参数传递。

最佳答案

在我回答你的帖子之前有几个问题......

“索引”在何处定义: vList = (short*)realloc(index, sizeof(short)*total);

您是否正在泄漏与以下内容相关的内存: short* list = new short [cnt];

您是否可能不小心混淆了内存分配中的指针?无论如何,这里有一个例子。你有一大堆问题,但你应该能够以此为指导来回答最初提出的这个问题。

工作示例:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int getTrimmedList(short** vList, short* vCnt);

int main ()
{
  // .. some codes here ..
  int err;
  short lstCnt;
  short *lstArr = NULL;
  err = getTrimmedList(&lstArr, &lstCnt);

  // list returned array (for comparison)
  for (int i=0; i<lstCnt; ++i)
    printf("lstArr[%3d] = %d\n", i, lstArr[i]);
  // .. some codes here ..

  return 0;
}

int getTrimmedList(short** vList, short* vCnt)
{
  short cnt = 5;
  short* list = new short [cnt];
  short* newList = NULL;

  short total = 0;
  list[0] = 0;
  list[1] = 3;
  list[2] = 4;
  list[3] = 6;
  total = 4;

  *vCnt = total;
  newList = (short*)realloc(*vList, sizeof(short)*total);
  if ( newList ) {
    memcpy(newList, list, sizeof(short)*total);
    *vList = newList;
  } else {
    memcpy(*vList, list, sizeof(short)*total);
  }

  delete list;

  return 0;
}

关于c++ - 数组作为 C++ 中的输出参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17333313/

相关文章:

c++ - 有没有办法在 clang 中检测 C++ 代码中的编译器 -fxxxx 标志?

C++11 可选模板类型参数?

php - 如何正确计算数组中的级别数?

arrays - 使用 schema.CreateTable 生成 SQL 字符串失败,postgresql ARRAY

c++ - 如何在 C++ 中将命令行参数的整个集合(char**)作为只读传递?

c++ - 与相应的 cpp 代码相比,为什么这个 bash 代码这么慢?

c++ - CMake:无法运行 MSBuild 命令:MSBuild.exe

c - 像一维数组一样初始化二维数组

c++ - 将 vector 的 vector 传递给函数

c++ - 为什么 std::atomic_fetch 将指针作为其输入参数