cprintflong-integer

printf char* pointer which points to long and float


I am doing some exercises from book "Understanding pointers in C". The book gives you a piece of code and asks you for what you get in output.

One of them is the following:

#include <stdio.h>

int main(int argc, char* argv[])
{
    char c, *cc;
    int i;
    long l;
    float f;

    c = 'Z';
    i = 15;
    l = 77777;
    f = 3.14;
    cc = &c;
    printf("c=%c cc=%u\n", *cc, cc);
    cc = &i;
    printf("i=%d cc=%u\n",*cc,cc);
    cc=&l;
    printf("l=%ld cc=%u\n",*cc,cc);
    cc=&f;
    printf("f=%f cc=%u\n",*cc,cc);
    return 0;
}

and the output is:

c=Z cc=1946293623
i=15 cc=1946293616
l=4294967249 cc=1946293608
f=0.000000 cc=4294967235

I don't understand why l and f are not printed as 77777 and 3.14?

I checked the book The C Programming Language to see if the if the printf's control chars are correct, and they are.


Solution

  • Try this:

    printf("l=%ld cc=%u\n", *(long*)cc, cc);
    printf("f=%f cc=%u\n", *(float*)cc, cc);