函数不会更改传递的指针C++
Function does not change passed pointer C++
我有我的函数,我正在那里填充targetBubble
,但在调用这个函数后没有填充,但我知道它是在这个函数中填充的,因为我有输出代码。
bool clickOnBubble(sf::Vector2i & mousePos, std::vector<Bubble *> bubbles, Bubble * targetBubble) {
targetBubble = bubbles[i];
}
我正在像这个一样传递指针
Bubble * targetBubble = NULL;
clickOnBubble(mousePos, bubbles, targetBubble);
为什么它不起作用?
因为您正在传递指针的副本。要更改指针,您需要这样的东西:
void foo(int **ptr) //pointer to pointer
{
*ptr = new int[10]; //just for example, use RAII in a real world
}
或
void bar(int *& ptr) //reference to pointer (a bit confusing look)
{
ptr = new int[10];
}
您正在按值传递指针。
如果要更新指针,请传递对该指针的引用。
bool clickOnBubble(sf::Vector2i& mousePos, std::vector<Bubble *> bubbles, Bubble *& t)
如果您编写
int b = 0;
foo(b);
int foo(int a)
{
a = 1;
}
您不能更改"b",因为a是b 的副本
如果你想更改b,你需要通过b 的地址
int b = 0;
foo(&b);
int foo(int *a)
{
*a = 1;
}
指针也是如此:
int* b = 0;
foo(b);
int foo(int* a)
{
a = malloc(10); // here you are just changing
// what the copy of b is pointing to,
// not what b is pointing to
}
以便更改b指向的位置以传递地址:
int* b = 0;
foo(&b);
int foo(int** a)
{
*a = 1; // here you changing what b is pointing to
}
hth
除非通过(非常量)引用或作为双指针传递,否则无法更改指针。传递值会生成对象的副本,对对象的任何更改都是对副本而不是对象进行的。如果按值传递,则可以更改指针指向的对象,但不能更改指针本身。
阅读一下这个问题,以帮助更详细地理解C++中何时通过引用传递和何时通过指针传递的区别?
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错