Question

I created a program called test:

#include<stdlib.h>
#include<iostream>
int main()
{
    std::cout<<system("..\\add\\debug\\add.exe 4 8");
    while(true);
    return 0;
}

add.exe consists of

#include<stdlib.h>
int main(int argc,char **argv[])
{
    int n=((unsigned)argv[1]);
    int m=((unsigned)argv[2]);
    return(n+m);
}

so when I run test, I get

6841420

The attempt was to have test run add with parameters 4 and 8, and for add to return the sum of those values (12) and then test would display that to the screen. How did I get 6841420, and how can I fix it?

Was it helpful?

Solution

The problem is that you are converting a pointer value into an integer. The arguments will be passed to your program as C style strings (const char*). You need to first convert these to a string using an API like atoi.

#include<stdlib.h>
int main(int argc,char *argv[])
{
    int n= atoi(argv[1]);
    int m= atoi(argv[2]);
    return(n+m);
}

EDIT

As others have pointed out, you should also do some error checking to ensure there are actually 2 parameters passed to the program.

OTHER TIPS

Your add.exe is casting pointers to strings to unsigned ints, so it's adding their positions in memory rather than the numbers.

Use sscanf (or, as suggested in another answer, atoi - it's probably easier).

This may be OK as a toy, but as an FYI, you can't count on being able to return the full range of integers from main(). First, system() uses various values as sentinels (-1 and 127, for example) so you wouldn't be able to tell the difference between a failed execution and a legitimate result of one of those values. Second, shells may limit the range of the return value to only 8 bits (using the remaining bits for additional status information).

The answers about using atoi() or sscanf() to convert argv[] elements from strings to actual integers are right on point.

There is another issue with your test case, however. The return value of system() is an exit status for the process that ran, which is more than a little platform dependent. However, on most platforms, things are arranged so that the value 0 means that the command ran ok, and eventually called exit(0) itself. Windows complies with that much.

The line cout<<system(...) is printing that status value. In many platforms (especially POSIX compliant ones) if the process ran without an abnormal termination than the low byte of the status code will be zero and the high byte will be the value passed to exit() assuming that value is 255 or less.

Actually using the exit status to communicate much more information than just success/failure to the parent process is highly platform dependent, and there are much better ways to do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top