-5

I am trying to make a board game with Maximum board width 80 cells and Maximum board height 52 cells, however the user should be able to choose the dimensions by entering them into the command line, so the dimensions could be smaller than the maximum. I am new to programming but i know that command line arguments are passed through the main function in C, I've just been stuck on this and cant seem to find any answers.

Can anyone help thank you.

Ibz
  • 1
  • 1
  • 2

1 Answers1

1

The main function takes two arguments, an integer usually called argc and an array of string pointers usually called argv. main is so usually declared as:

int main(int argc, char *argv[])

The argc variable is the number of arguments passed to your program.

The argv variable is contains the actual arguments pass to your program.

The argc variable is at least equal to 1, as the actual program name is always passed as an argument, and is in argv[0].

If you want two arguments, then you first have to make sure that argc is at least equal to 3. The first argument to your program is then stored as a string in argv[1], and the second is in argv[2].


I recommend you experiment with a program such as this:

#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("argc = %d\n", argc);

    for (int i = 0; i < argc; i++)
        printf("argv[%d] = \"%s\"\n", i, argv[i]);

    return 0;
}

And finally (and unrelated to your problem but interesting none the less) is the fact that the size of the argv array is actually one larger than most people expect. The size of the argv array is actually argc + 1 and so can be indexed from argv[0] (the program name) to argv[argc]. This last entry (argv[argc]) is always a NULL pointer.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • thank you that makes sense, there is just one thing, you said the argument is stored as a string and i need it to be an integer because its supposed to be the dimension of the board. – Ibz May 10 '13 at 13:04
  • @Ibz You should read about the function [`strtol`](http://en.cppreference.com/w/c/string/byte/strtol). – Some programmer dude May 10 '13 at 13:08