Search code examples
arrayscpointersinteger

why *ptr is not working while using float array, did I mistake with the wrong format specifier or something else?


In this code i was trying to print the array using pointer but it just doesn't work with float array. Note: i have done this exact same code with int array and it was working fine and as expected but this on the other hand is miserable. Float array is the problem i guess.

CODE:

#include<stdio.h>

int main(){

    

    float arr[]= {1, 2, 3, 4, 54};
    int *ptr ;
    ptr = arr;


    printf("%u\n", ptr);
    printf("%u\n", *ptr);
    printf("%d", &ptr);

}


i am expecting this output.

OUTPUT: address of arr[0] . value of arr[0] . address of ptr


Solution

  • To begin with you use a pointer to an int to point to your array. That needs to be float * to be correct:

    float *ptr = arr;
    

    Then lets take the printf statements one by one...

    We start with:

    printf("%u\n", ptr);
    

    Here ptr is a pointer. The format %u is to print an unsigned int value. To print a pointer you need to use the %p format. And the pointer need to be a void * pointer. Mismatching format specifier and argument type leads to undefined behavior.

    Second:

    printf("%u\n", *ptr);
    

    Once you fix the pointer issue mentioned first, then you use *ptr which is the same as ptr[0] which is a single float value. The recommended format to print a float (or a double) value is %g or %lg. Again you have mismatching format specifier and argument type.

    Lastly:

    printf("%d", &ptr);
    

    Here &ptr is a pointer to the variable ptr itself. It will have the type float **. As before you have mismatching format specifier and argument type.

    To solve your problems you need to use correct specifier and arguments:

    printf("%p\n", (void *) ptr);
    printf("%g\n", *ptr);  // ptr[0] would also work
    printf("%p", (void *) &ptr);
    

    Most compilers available today should be able to detect these kind of problems and issue warnings about them. You might need to enable more warning to get the warnings. Always treat warnings as errors that must be fixed.