apusateri
apusateri

Reputation: 58

Pointer to double initialization

I'm certain that I'm missing something basic here, trying to figure out why I'm getting the following output.

#include <stdio.h>

int main(int argc, char** argv) {
  double val1 = 20.0;
  double *p1;
  p1 = &val1;

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

  return 0;
}

Output:

p1 is 0.000000

However, if I print the value of val1 before p1, it seems to be assigned to the correct value.

#include <stdio.h>

int main(int argc, char** argv) {
  double val1 = 20.0;
  double *p1;
  p1 = &val1;

  printf("val1 is %f\n", val1);
  printf("p1 is %f\n", p1);

  return 0;
}

Output:

val1 is 20.000000 
p1 is 20.000000

Upvotes: 0

Views: 54

Answers (3)

Sinstein
Sinstein

Reputation: 909

To refer to the value at the memory location pointed to by the pointer, you need to de-reference it.

double *p;

The value is then obtained by *p and not p alone. Remember that p is merely the pointer.


For your example:
printf('p1 is %f\n",*p1)

Upvotes: 1

rodrigo
rodrigo

Reputation: 98446

Well, you are passing to printf the pointer to double, not the double:

printf("p1 is %f\n", *p1);

That should do it!

Note 1: Beware! passing the wrong type to printf (in this case, a double* instead of a double will cause Undefined Behavior.

Note 2: Arguments to variadic functions, such as printf will suffer arithmetic promotions, so float values will be passed as double, short and char as int, and so on. So you can pass float and double for a %f format specification without trouble.

Note 3: But beware! float* will not be promoted to double*, because it is not an arithmetic type (it is a pointer). That's why the *scanf() family of functions has much more format specifiers than the *printf: because the former take pointers and the latter values.

Upvotes: 4

Arun
Arun

Reputation: 20383

printf("p1 is %f\n", *p1);
                     ^

Upvotes: 2

Related Questions