Passing arguments to main in C using Eclipse

556 Views Asked by At

I have a program in Eclipse and I need to pass some arguments into main.

More specifically, I need to pass 2 strings (which are numbers) and are needed to call some other functions. Here is my main:

int main(int argc, char **argv) {
    int n = atoi(argv[0]);
    size_t size = (size_t)(atoi(argv[1]));
    char **commands = getCommands(n, size);
    return 0;
}

What getCommands doesn't matter, as my questions are:

1) Is my use of atoi correct here? Let me remind you that the arguments I want to pass is an array of strings, where the strings are numbers. Also, will the int from atoi get successfully converted into size_t just by casting it?

2) What exactly do I have to put in the arguments box in Eclipse? When I pass : 2 {"3","50"} it doesn't work. Aren't I supposed to pass first the number of arguments in the array, and then the array of strings? I am a bit confused. This also goes to passing arguments from the command line, as I guess it has to have the same format? I don't know how to do that either.

Thanks.

1

There are 1 best solutions below

0
On BEST ANSWER

1) Sure, that's all fine (except for the argv indices as described below), if you're assuming your inputs are valid numbers. If not, atoi will return 0.

2) You're not meant to pass arguments to main -- instead, you pass arguments to the program, and the OS comes up with the right arguments to pass to main. So rather than passing 2 {"3","50"}, you just pass in 3 50. In your main function, you'll see that argc == 3, argv[0] is the name of the program, argv[1] is the string "3", and argv[2] is the string "50".