The following code calculates the greatest common divisor of two numbers. I have been trying to make sense of it, however, I have a few questions about it.

Code: Select all
`#include <iostream>#include <cstdlib>using namespace std;int gcd(int a,int b);int main(int argc,char *argv[]){  int a, b;  if (argc != 3) {    cout << "SYNTAX: " << argv[0] << " <num1> <num2>" << endl;    cout << "Returns the greatest common divisor of num1 and num2." << endl;    return -1;  }  a = atoi(argv[1]);  b = atoi(argv[2]);  cout << "The greatest common divisor of " << a << " and " << b;  cout << " is: " << gcd(a,b);  return 0;}int gcd(int a,int b){  int t;  while(b) {    t = b;    b = a % b;    a = t;  }  return a;}`

Starting from the top, there is a "*" before argv[], what does that do? I know that argc is the number of arguments, and I understand that there will be 3 arguments for this code, gcd, then two numbers. the if (argc != 3) part is making sure the user entered gcd and then 2 numbers (or two arguments), but after that...what does atoi do? other than this I understand the code...I think.
traveler247
New User

Posts: 4
Joined: Sat Jan 10, 2009 10:41 pm
Blog: View Blog (0)

### Re: questions about some code

You may see either of:
- char **argv
- char *argv[]
- char argv[][]

The first two are pretty common, while the last one is rarely used.
Knowing what you do, argv is an array of strings.
Not knowing what you do, or not yet understanding, argv is an array of strings, while strings are arrays of characters. Basically, a two-dimensional array.
Arrays are nothing else than pointers, so you can use either notation to refer to them as parameter. However, it does make a difference when you declare a variable of that type (rather than using it as parameter), since one allocates memory on the stack, while the other does not.

argc (Argument Count) and argv (Argument Vector) are used to provide access to command line arguments.
argc is always >= 1 and never 0, since argv[0] is always the name of the application itself.
If you want to check for exactly two arguments (as your example does), you check if (argc == 3) (or the other way round, checking for everything except 3 and showing an error instead).

atoi started off as Any TO Integer, but since it does not do any input verification, it should be avoided unless you absolutely know what you're doing. You maybe want to look into strtol (string to long, long is just a 32-bit integer) if you get some time to improve it

- BhaaL
BhaaL
Poster

Posts: 270
Joined: Sun Apr 13, 2008 11:16 am
Blog: View Blog (0)

### Re: questions about some code

thank you, that helped me a lot, and I'll definitely look into using strtol, thanks again!
traveler247
New User

Posts: 4
Joined: Sat Jan 10, 2009 10:41 pm
Blog: View Blog (0)