Search code examples
cpointerscommand-line-argumentsargv

Why are my integer values not being displayed or calculated correctly in C?


By trade I'm a PHP programmer and wanted to test writing a C program, sending it arguments and using it's output in PHP using shell_exec().

Anyway, I wrote this code simply to add two numbers together:

#include <stdio.h>

int leftop, rightop, result;

int main(int argc, char *argv[])
{
    leftop = (int) argv[1];

    rightop = (int) argv[2];

    result = leftop + rightop;

    printf("The result of %i add %i = %i\n", leftop, rightop, result);
    getchar();
    return 0;
}

i compile it with MinGW using gcc -o main.c mycprogram.exe.

When I run the program (either using shell_exec() (php) or from command line) I get the following results.

./mycprogram.exe 25 25

The result of 7150824 add 7149184 = 14300008

then i run it again and get:

The result of 6692040 add 6692072 = 13384112

obviously I expect the result to be 50.

How come I'm not getting the correct results?


Solution

  • The problem is, argv[1] (argv[n], in general) is a pointer to a string cating that to int does not give you the corresponding integer which you might have passed as argument.

    That said, the validity of the statement(s) like

     leftop = (int) argv[1];
    

    are heavily implementation dependent, as validity of pointer-to-integer conversion is implementation specific behaviour. In some of the cases, it causes undefined behavior.

    Solution: You should be using strtol() to convert the string to integer type.