Why am I getting a strange number in this code?

后端 未结 5 1336
甜味超标
甜味超标 2021-01-28 11:20

I want to write a C program that evaluates the factorials of the integers from 1 to 5 and print them in a tabular format. However, I keep getting a strange number over everythin

5条回答
  •  鱼传尺愫
    2021-01-28 11:52

    Unlike scanf, printf() with format %d requires integer values, not addresses (&x is the address containing an integer, so a pointer to integer which type is int *). The correct expression is

    printf("%d\t %d\n", x, factorial);
    

    Why was the previous expression wrong?

    With printf("%d\t %d\n", &x, &factorial); you are asking to printf to print the decimal representations of the addresses of x and factorial respectively.

    For this reason it is not surprising that the values that used to be printed, 6356768 and 6356772:

    1. Are big numbers, multiples of 4 (because they address integers, that have a size 4 bytes, and in 32 bits architectures like yours are aligned to memory locations multiples of 4)
    2. They are memory locations, and their addresses do not vary even if their contents are changed

    You can find printf documentation here.

提交回复
热议问题