Can anybody tell me why this is happening in c language

前端 未结 3 1258
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 16:55
 #include 
 //Compiler version gcc 6.3.0

 int main(void)
 {

     float a=10;
    printf(\"%f\"+1,a);

    return 0;
 }

Output -- d

相关标签:
3条回答
  • 2021-01-29 17:25

    I am not sure what exactly are you trying to accomplish.

    If you want to do the sum, you just have to do it after the comma:

    from this:

    printf("%f"+36,a);
    

    to this:

    printf("%f",a+36);
    

    The same for the other sum.

    0 讨论(0)
  • 2021-01-29 17:27

    You should definitely compile with all warnings. I used gcc -Wall -Wextra -Werror -pedantic. It didn't compile with my warnings because there are too many arguments for printf.

    When I tested out the code you posted, it printed 'f' and 'A???'. I'm not sure what you're trying to do, but I believe it has to do with how your float is adding with the number to give you an Ascii character.

    0 讨论(0)
  • 2021-01-29 17:32

    The output is different every time because it is undefined to read from an unknown address.

    Compare with this code:

    #include <stdio.h>
    
    int main(){
    
       printf("Hello,World\n"+1);
    }
    

    It looks like the famous Hello,World but in fact it is the less known version ello,World. The argument to printf is string or more precisely a pointer to a null terminated sequence of chars in memory, when "Hello"+1 is evaluated, the pointer is incremented by one and points to "ello,World".

    Your program will first print the the string "f" and in the second case is a memory overrun error, it will print whatever is found in the memory location 36 bytes away from the string. This random memory location is likely to have a different contents every time.

    0 讨论(0)
提交回复
热议问题