c++ - 从 int 到 int** C++ 的无效转换

标签 c++ pointers casting

不确定为什么会出现此错误。我有以下内容:

int* arr = new int[25];

int* foo(){
   int* i;
   cout << "Enter an integer:";
   cin >> *i;
   return i;
}

void test(int** myInt){
   *myInt = foo();
}

This call here is where I get the error:

test(arr[0]);   //here i get invalid conversion from int to int**

最佳答案

按照您编写的方式,test 接受一个指向 int 的指针,但是 arr[0] 只是一个 int

但是,在 foo 中,您提示输入一个 int,但读入的位置是未初始化指针的值。我以为您希望 foo 读取并返回 int

例如

int foo() {
   int i;
   cout << "Enter an integer:";
   cin >> i;
   return i;
}

在这种情况下,测试采用指向 int 的指针(即 void test(int* myInt))是有意义的。

然后您可以将指针传递给您动态分配的 int 之一。

test(&arr[0]);

关于c++ - 从 int 到 int** C++ 的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2677907/

相关文章:

c# - 如何在 VS 2013 中调试 Windows Phone (8) 运行时组件或 C++ DLL 中的 C++ 代码

c++ - 为什么模板只能在头文件中实现?

c++ - 什么是覆盖共享内存?

c++ - 用于具有不同签名的函数的枚举切换器

c# - 如何在 C# 中从数据读取器中转换为空 boolean 值?

c++ - 在C++中使用curl获取一段时间后更改的页面

c++ - 使用指向非静态成员函数的指针实现回调

c - 在文件流中后退一位

c++ - 我正在尝试计算 char 数组中的内容直到空终止,但每次编译时我得到的数字都大于我的数组

c++ - C/C++ 中的显式转换