从动态数组中获取价值(C ++)

时间:2017-04-18 22:09:42

标签: c++ arrays

我有一个以这样的方式返回数组的方法:

int *compare() {
    int result[2] = {10, 20};
    return result;
}

使用代码int *match = compare();,我可以获得10还是20

4 个答案:

答案 0 :(得分:3)

使用C ++,您确实应该使用标准容器,例如std::vector<>。这样做,您的示例代码可能是

std::vector<int> compare() {
    std::vector<int> result {10, 20};
    return result;
}

如果确实想要返回指针(为什么?),请至少使用std::unique_ptr<>将所有权传回给调用者。该代码看起来像

std::unique_ptr<int[]> compare() {
    std::unique_ptr<int[]> result(new int[] { 10, 20 });
    return result;
}

但使用std::vector<> 首选。

答案 1 :(得分:1)

如果不是编译器错误,那么你有什么未定义的行为。 您的数组在堆栈上并且是您的函数的本地数组。当函数返回并且消失时,它超出范围。

你需要使用operator new在堆上分配它才有意义。如果你这样做,建议你返回一个std :: unique_ptr,这样调用者就知道有处理分配的对象,如果没有抓住则返回处理清理。

答案 2 :(得分:1)

你可以这样做:

int *compare(int result[])
{
     result[0] = 10;
     result[1] = 20;
     return result;
   }

 int main()
 {
    int result[2];
    int *match = compare(result);
    cout << *match << endl;
    cout << *(match + 1) << endl;
 }

你不能返回局部变量的地址,因为在返回语句之后该变量内的任何内容都会消失。

答案 3 :(得分:0)

  

您必须使用以下动态分配方法之一;

  • malloc() - 分配请求的字节大小,并返回分配空间的指针第一个字节。
  • calloc() - 为数组元素分配空间,初始化为零,然后返回指向内存的指针。
  • - 仅关键字cpp not c
int *compare() {
     int *result =  (int*)calloc(2,sizeof(int)); // or cpp -> new int[2];
     result[0] = 10;
     result[1] = 20;
     return result;
}