简体   繁体   English

无效指针转换 C++

[英]invalid pointer conversion C++

I'm happy to post my first question here .我很高兴在这里发布我的第一个问题。

so i was play a little bit with pointers to understand the concept and i found this error所以我玩了一点点来理解这个概念,我发现了这个错误

error: invalid conversion from 'int*' to 'int' [-fpermissive]错误:从“int*”到“int”的无效转换 [-fpermissive]

here is the code :这是代码:


#include <iostream>

using namespace std;

int main(){

    int* pa,pb,pc,a,b,c;

    pa = &a;
    cin >> a;
    cout <<"the value of a :"<<a<<endl;
    cout <<"the value of pointer of a :"<<*pa<<endl;

// the problem begins when reading values of b :

    pb = &b; //<== error 
    cin >> b;

    cout << "the value of b : "<<b<<endl;
    cout <<"the value of pointer of b" <<*pb<<endl;
    
    return 0;
}

i don't know why it went successfully with variable a but failed with the same syntax in b ?我不知道为什么它用变量a成功a但在b中用相同的语法失败了?

EDIT : thanks for everyone , i know this question is very simple but i've learned from you :)编辑:谢谢大家,我知道这个问题很简单,但我已经向你学习了:)

The * binds to the variable name, not the type. *绑定到变量名,而不是类型。 So what you really want is:所以你真正想要的是:

int *pa,*pb,*pc,a,b,c;

In the declaration在声明中

int* pa,pb,pc,a,b,c;

Only pa is declared as int* .只有pa被声明为int* The other variables are declared as int .其他变量声明为int

You would need to declare the variables as您需要将变量声明为

int *pa, *pb, *pc, a, b, c;

A common recomendation is to declare one variable per line (see for example ES.10: Declare one name (only) per declaration ), because * belongs to the variables, not the type and this can be confusing.一个常见的建议是每行声明一个变量(参见例如ES.10:每个声明声明一个名称(仅) ),因为*属于变量,而不是类型,这可能会造成混淆。 Your你的

int* pa,pb,pc,a,b,c;

is actually实际上是

int* pa;
int pb;
int pc;
int a;
int b;
int c;

But you wanted:但你想要:

int* pa;
int* pb;
int* pc;
int a;
int b;
int c;

In other words, you get the error becaue in your code pb is an int but &b is an int* .换句话说,你得到错误是因为你的代码pb is an int&b is an int* The first assignment is ok, because pa is a pointer.第一个赋值没问题,因为pa是一个指针。

Another common recommendation is to always initialize your variables (see ES.20: Always initialize an object ), so even nicer would be另一个常见的建议是始终初始化您的变量(请参阅ES.20:始终初始化一个对象),这样更好

int a = 0;
int b = 0;
int c = 0;
int* pa = &a;
int* pb = &b;
int* pc = &c;

And once you got it straight what type pa , pb and pc are you can use auto to get "just the right type":一旦你弄清楚papbpc是什么类型,你就可以使用auto来获得“正确的类型”:

auto a = 0;     // 0 is an integer literal of type int
auto b = 0;
auto c = 0;
auto* pa = &a;  // auto would be fine too, &a is a int*
auto* pb = &b;
auto* pc = &c;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM