Mohamad Ibrahim
Mohamad Ibrahim

Reputation: 5575

cast a pointer to int in C

I have this array "r->phy_addr" defined as follows:

int array [r->numpgs];
r->phy_addr= &array[0];

now I want to pass element zero of the array to a function that takes "int" as an arugument:

add(int x){};

if I do like this

add(r->phy_addr[0]);

then an error of "can't pass a pointer as an int"

How can I do it?

Upvotes: 2

Views: 173

Answers (4)

Jessica Larris
Jessica Larris

Reputation: 29

try add(*(r->phy_addr[0])); it should work

Upvotes: 2

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

If the compiler complains about r->phy_addr[0] beng a pointer, then r->phy_addr must have pointer-to-pointer type (int ** most likely). In that case your problems begin even earlier. This

r->phy_addr = &array[0];

is already invalid, since you are assigning int * value to a int ** object. The compiler should have told you about it.

In other words, your call to add is not a problem. Forget about the call to add. It is too early to even look at that call. You have other problems that have to be solved well before that one.

What is r->phy_addr? Is it supposed to have int ** type? If so, why are you assigning it as shown above? Why are you ignoring compiler diagnostic messages triggered by that invalid assignment?

Upvotes: 3

Chul-Woong Yang
Chul-Woong Yang

Reputation: 1243

I suspect that r->phy_addr has int ** type. So r->phy_addr[0] gets int * type, and then compiler warns you that the argument should be int type, rather than int * type.

Change the type of r->phy_addr to int *.

Thanks.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258678

How about:

add(*(r->phy_addr[0]));

? Since, apparently, r->phy_addr[0] is a pointer.

Upvotes: 0

Related Questions