Iheb
Iheb

Reputation: 23

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]

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 ?

EDIT : thanks for everyone , i know this question is very simple but i've learned from you :)

Upvotes: 2

Views: 214

Answers (3)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122238

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. 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*. The first assignment is ok, because pa is a pointer.

Another common recommendation is to always initialize your variables (see ES.20: Always initialize an object), so even nicer would be

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":

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;

Upvotes: 4

Rotem
Rotem

Reputation: 21917

In the declaration

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

Only pa is declared as int*. The other variables are declared as int.

You would need to declare the variables as

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

Upvotes: 5

Mark Ransom
Mark Ransom

Reputation: 308130

The * binds to the variable name, not the type. So what you really want is:

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

Upvotes: 5

Related Questions