简体   繁体   中英

Divide Executable with Parameters through cmd in c not working

I'm trying to create a neural network using a batch file. The only problem is that batch doesn't support floating point numbers. So, I decided to make an executable in c in which you could pass in 2+ parameters, for example: "divide 5 3" in the cmd, and it would divide the parameters. Here is my program:

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

int main(int argc, char* argv[]) {
    float num1 = atoi(argv[1]);
    float num2 = atoi(argv[2]);
    if (argc > 2) {
        printf("%f", num1 / num2);
        return EXIT_SUCCESS;
    }
    else {
        printf("3 arguments expected\n");
        return EXIT_FAILURE;
    }
}

Of course, this doesn't work, and yes, I have tried to change the numbers a bit and made countless versions of this program. I couldn't find a solution online. Last time you guys helped me a lot, hope you can again!

Adding a newline to the output and running it:

$ ./div
Segmentation fault
$ ./div 1
Segmentation fault
$ ./div 1 3
0.333333

You're reading from argv[1] and argv[2] before checking argc to see how many arguments you have.

With zero or one arguments one or both of them will contain garbage, which not surprisingly leads to a segfault when it tries to read from some random location. (Or maybe there was a guaranteed NULL at the end of argv . I can't remember, but it doesn't matter, you still get a segfault.)

Regarding that error message, I would say "2 arguments expected", not 3, since usually the user won't count the program name, even though the number in argc includes it.

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