I am having a requirement where in I need to call a C++ application from command line and need to pass a two dimensional array of int type to it. Can anyone please let me know how to do that, and how to interpret it in C++ application using argv parameter
thanks in advance.
In argv
you can pass only a one dimensional array, containing strings, it's
char* argv[]
So, you can't really pass 2D array, but you can "simulate" it.
For example, pass 2 parameters, saying what are the sizes of the matrix - number of rows and number of columns and then pass all elements, one by one.
Then parse the arguments in your program, knowing what format you will use.
For example: if you want to pass
1 2 3
4 5 6
you may run your program like this:
./my_program 2 3 1 2 3 4 5 6
This way, you'll know, that argv[1]
is the number of rows, argv[2]
s the number of columns and them all elements of the 2D array, starting from the upper left corner.
Don't forget, that argv
is array, containing char*
pointers. In other words, you'll need to convert all parameters int
s.
I would recommend passing a file as the only argument. Or data in the same format on stdin as @j_random_hacker suggests. If no human needs to edit it, it could be a binary file. One possible format:
4 bytes = size of first dimension
4 bytes = size of second dimension
4 bytes * size of first * size of second = contents of array
When reading, everything is aligned. Just read every four byte int and interpret as above.
If it needs to be human readable I would do csv or space-delimited. There would be no need to specify the dimensions in that case because each row ends in newline.