OkCloudy
OkCloudy

Reputation: 19

%d vs %f format specifier (not sure of output): C

I get that %d is the format specifier for type decimal, and %f is for float, but I'm not sure why the output of the 2nd print statement is 3.

#include <stdio.h>

int main()
{
    float arr[5] = {12.5, 10.0, 13.5, 90.5, 0.5};
    float *ptr1 = &arr[0];
    float *ptr2 = ptr1 + 3;
 
    printf("%f ", *ptr2);
    printf("%d", ptr2 - ptr1);
 
   return 0;
}

Upvotes: 1

Views: 161

Answers (1)

hryrbn
hryrbn

Reputation: 321

So, you seem to have pointer arithmetic mostly down, since you understand why *ptr2 equals 90.5, but you're missing a piece here. You have to remember that ptr1 and ptr2 on their own refer to memory addresses - which are integers - and not the floating point numbers stored at those addresses. The difference of addresses ptr2 and ptr1 is 3, as you set in the line float *ptr2 = ptr1 + 3.


I can't tell exactly what your goal is here, but if you are trying to print an integer of the difference of the floats stored at those addresses (which I think you are), you'll need to dereference the pointers and perform a type cast. The final line before return 0 should be printf("%d", (int)(*ptr2 - *ptr1)). This prints 78 to the console.

But, that's only if the "assignment" here is to specifically use an integer. Realistically, it would be written more like printf("%0.f", *ptr2 - *ptr1), which keeps the number as a float but will not print anything after the decimal point.

Upvotes: 2

Related Questions