简体   繁体   中英

C Program to add 2 integers produce abnormal output

I've already looked all over the internet but haven't found anything related to this.

Here's the output

Enter First Number: 2
Enter Second Number: 3
Total: 6422308Press any key to continue . . .

Here's the code


#include <stdio.h>
#include <stdlib.h>

int main() {

    int num1;
    int num2;

    int total;

    printf("Enter First Number: ");
    scanf("%i", &num1);

    printf("Enter Second Number: ");
    scanf("%i", &num2);

    total = num1 + num2;

    printf("Total: %i", &total);
    system("pause");

    return 0;
}

Well, I expect the output to be proper

Your Problem The line printf("Total: %i", &total); should be changed to printf("Total: %i", total);

The Reason The & unary operator in C gets the address of the operand(variable). Notice in the usage of scanf you need the '&' operator. The reason why you need it for scanf is because the variable needs to be modified outside of the scope of the calling function(the scope of main() in our case). On the other hand printf just needs the value of the variable, so just the variable name total is needed.

To Clarify 0x6422308 is the address in memory where the variable total is located which is equivalent to &total .

You are currently printing the memory address of total, and not what the value stored in that memory address is. This is because c utilizes pointers, allowing you to set memory addresses, access information from memory addresses, and use pointer arithmetic to sift through memory. When prefixing a variable with the & operator, you are essentially declaring that you want the memory address that variable is stored in. If you wanted the value of a memory address, you would have to dereference the memory address with the * operator. I haven't tried this, but you could do something like printf("Total %i",*(&total)) to dereference the memory address of total to get the value.

The above is a way too complicated for this application however, and you do not need to mess with memory addresses in printing for this case. Therefore, you can just pass the variable total to printf and everything will be good (since total is not a pointer).

Remove the & inside of your total printf and everything should work correctly. You can see how to use printf and scanf here

&x stands for the address of the variable x . So scanf(..., &x) makes sense because the function scanf requires an address of a variable for putting data. And printf(&x) outputs an address of the variable x , instead of value of this variable. You should use printf(x) to obtain the expected result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM