0
/* test1.c */
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int m = 11;
    system("./test2 m");
    return 0;
}

The above program prints 0, whereas I expect it to print 11.

/* test2.c */
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int m = atoi(argv[1]);
    printf("%d\n", m);
    return 0;
}

Can someone provide an explanation? Also what would be the right way in order to print the desired 11?

1
  • 1
    It's your own fault to refuse to check whether the integer parsing succeeded. Making blind assumptions at every step is not the way to write programs. Commented Nov 15, 2013 at 11:25

3 Answers 3

4

You are passing the character m to the command line, not its value.

Sign up to request clarification or add additional context in comments.

Comments

3

The system() function just takes a string as its argument. It doesn't know that you have a variable named m and that it should substitute that variable in the string (Which would not be possible in C anyways with such a syntax.)

That means you are executing your second program like this:

 ./test2 m

Your 2 program does atoi(argv[1]); , which will then be the same as atoi("m"); , which makes atoi() return 0.

You need to build up the string you want system() to execute

int main(int argc, char *argv[])
{
    char command[128];
    int m = 11;
    sprintf(command , "./test2 %d", m);
    system(command);
    return 0;
}

Comments

3

C does not expand variables in string constants like perl so m in your command string is a string constant.

What you need to do is print the value of mto the command string:

/* test1.c */
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int m = 11;
    char buf[100];
    sprintf(buf, "./test2 %d", m);
    system(buf);
    return 0;
}

4 Comments

Funny how we came to the same solution here, y? But you forgot int before m ;)
Thanks. My mistake was that I assumed test1.c was compiling, so I didn't scan for syntax errors. And not strange at all that they are the same, because it is the simplest and most straightforward solution.
I have this thread running in my head which scans for syntax errors all the time. Stops working about 2am, though.
I let the compiler do that, so my cores can focus all their processing cycles on semantic errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.