C++返回并使用指针
C++ Returning and Using a Pointer
例如,假设我有一个这样的函数,它旨在返回指向数组的指针。
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.
相关文章:
- 在 const 函数中通过引用和指针返回之间的区别
- 指向 std::unrodered_map 中元素的指针返回'Read access violation'
- 为什么要为指针返回类型返回一系列字符?
- Visual C 运行时:Malloc将指针返回到已经使用的内存(包含实际字符串)
- 将原始指针返回到智能指针
- 从函数中的指针返回对象,例如链接列表
- 将指针返回使用New创建的数组数组
- 查找并将指针返回向量中的对象
- 函数可以将指针返回其自己的类型
- 指针返回值的地址
- 为什么静态指针返回函数中有一个"静态"键?
- 从弱指针返回类型返回共享指针
- 如何将C++引用和指针返回转换为 C++/CLR
- 从指针返回对象时出现意外的析构函数调用
- 阵列指针返回垃圾
- (C )当在同一类中调用时,污点指针返回正确的值,而从MAIN调用时为0
- C 从指针返回到成员功能
- 在构造函数以外的任何其他位置访问相机时,我的相机指针返回 null
- 从取消引用的指针返回原始指针
- 指针返回