这个问题在这里已有答案:
我是C / C的初学者,我正在努力学习指针 .
这是我的代码,用指针数组中的每个元素创建指针数组,指向数据数组中的元素:
#include <iostream>
using namespace std;
//Pointers reference article
//https://www.programiz.com/cpp-programming/pointers-arrays
/* Array of pointers */
const int MAX = 5;
int main(){
int arr[MAX] = {1,2,3,4,5};
int* ptr[MAX];
cout << "Create the handle of each element in data array to the ptr array: " << endl;
for (int i=0; i<sizeof(arr)/sizeof(arr[0]);i++)
{
ptr[i] = &arr[i];
cout<<"ptr["<<i<<"] = " << ptr[i] << endl;
}
cout << "Display the contents of array using 1:1 ptr array:"<< endl;
for (int i=0; i<sizeof(arr)/sizeof(arr[0]);i++)
cout<<"arr["<<i<<"] = " << *ptr[i] << endl;
system ("pause");
return 0;
}
上述程序按预期工作 . 但是,如果我在指针声明期间将指针类型从int更改为void,即来自int * ptr [MAX];无效* ptr [MAX];
我有这个错误:cpp(22):错误C2100:非法间接
Line 22: cout<<"arr["<<i<<"] = " << *ptr[i] << endl
有人可以告诉我这个错误 . 提前致谢 .
2 回答
ptr
是指向int
的指针数组 .当你改为
那么
ptr
是一个指向void
的指针数组 . 这不会导致第一个错误cout
但这是第二个错误:
你不能取消引用
void
指针 - 这就是错误 . 指针必须是要取消引用的特定类型 .你需要问自己一个问题 - 虚空是什么意思?
所以你有一个void指针 - 这意味着它指向了void
这可以是任何东西 - 任何int,A结构,一个对象,一个浮点....
得到照片
然后编译器试图去引用它 - 所以它举起手来说 - 我没有线索 .
无论是哪种情况 - 或者更好的是仍然避免无效指针