Eric
Eric

Reputation: 21

error: pointer value used where a floating point value was expected

This is not homework, but my last assignment made it clear that I didn't clearly understand pointers when coding C.

Therefore, I tried to type a simple program using pointers just to invert an integer in a function, so I could figure out where the gap in my understanding is.

Apparently, I've arrived at it, but I still cannot figure out what I am doing wrong.

My source code is below.

#include <stdio.h>

float invert(int *num);

void main (void)
{
int num;
float a;

printf("enter an integer \n");

scanf("%i", &num);

printf("Number entered %i \n", num);

a=invert(&num);

printf("This is the invse from main %f \n", a);

}


float invert(int *num) /* function inverts integer */

{       
float invse;

printf("num is %i \n\n", *num);

invse = 1/(float)num;

printf("invse is %f \n\n", invse);

return(invse);

}

My thinking was that I used the pointer to direct the computer to use the value stored at the address for num in the function invert(). The pointer appears in the variable declaration. I cast the value stored at that pointer as a float, so I could invert it, and store it in a local variable.

The problem appears to be in the local variable assignment. My compiler returns "invert.c:29:2: error: pointer value used where a floating point value was expected invse = 1/(float)num; ^

Apparently my code indicates a pointer value for inverse, but I declared it as a float, which I find confusing.

Any help is appreciated. This will save me on completing my larger set of code for my assignment, which I did not post here.

Thanks.

Upvotes: 2

Views: 14102

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320739

Judging by the printf call inside invert

printf("num is %i \n\n", *num);

you already know that in order to access the value passed to invert for inversion you have to dereference num pointer: *num.

If so, then why aren't you dereferencing num when you perform the inversion itself?

invse = 1/(float)num;

I mean, if you are the one who wrote that printf, you should also realize that the actual inversion should be done as

invse = 1 / (float) *num;

or, alternatively, as

invse = 1.f / *num;

On top of being incorrect your original variant is illegal: you are not allowed to convert pointers to floating-point types in C, which is the reason for the error message.

P.S. From the bigger picture point of view, there's no real reason to pass that the number to invert by pointer. Passing the immediate value would make more sense

float invert(int num)
{
  ...

In that case you, of course, don't have to dereference anything inside invert.

Upvotes: 1

Related Questions