C++返回并使用指针

C++ Returning and Using a Pointer

本文关键字:指针 返回 C++      更新时间:2023-10-16

例如,假设我有一个这样的函数,它旨在返回指向数组的指针。

int*   oddInRange(int low, int high){
int odds[someLength];
// Some code to fill the array.
return *odds; // Is this the correct way to return?
}

然后一旦我返回指针。我将如何使用它并从中获取值?

int* testOdds = oddsInRange(1,10);
// What do I need to do with testOdds to get the values
// that were generated in the function above?

我知道我可能不需要在这里使用指针,但这是为了学习。

 return *odds;

是一个错误,因为*odds计算结果为 int ,这与返回类型不匹配。您可以使用

 return odds;

但这会在运行时导致问题,因为一旦函数返回,指针就会无效。

最好使用std::vector并避免数组的所有问题。

std::vector<int>  oddInRange(int low, int high){
   std::vector<int> odds(someLength);
   // Some code to fill the array.
   return odds;
}

这将不起作用;您的数组在堆栈上分配,因此在函数退出后不可用。

在您的情况下,您需要执行以下两件事之一 - 从调用方创建一个数组并将其传入,或者动态分配一个数组并返回它。以这个动态分配数组为例:

int*   oddInRange(int low, int high){
    int* odds = malloc(sizeof(int) * someLength);
    // Some code to fill the array.
    return odds; // Is this the correct way to return?
}

或填写:

void oddInRange(int* odds, int low, int high) {
    // Do stuff to odds
}
// And to call...
int* myArr = malloc(sizeof(int) * someLength);
oddInRange(myArr, 1, 2);

无论如何,如果我们忽略堆栈分配问题一秒钟,你的代码仍然是错误的。你想要获取一个指向数组的指针。在 C 语言中,数组变量可以隐式衰减到指针,因此您无需使用 &* 来获取指向数组的指针,只需使用名称即可。您也可以获取第一个元素的地址。举这些例子:

int myArray[10];
int* myArrayPtr = *myArray; // What you had. Incorrect.
int* myArrayPtr = myArray;  // OK - arrays decay to pointers to the first element.
int* myArrayPtr = &myArray[0]; // Also OK.