The books tells me The declaration of the main looks like this:
int main(int argc, char* argv[])
or int main(int argc, char** argv)
It seems that int argc, char** argv are the only things I can send as actual parameters.
Now I don't want to deal with strings main.
I want to calculate the sum of integers sent to main and return the sum.
#include
<iostream>
int main(int n, char** argv) {
std::cout << n << std::endl;
char** temp = argv;
int sum = 0;
int i = 0;
while (*temp != NULL) {
std::cout << i++ << ':' << *temp << std::endl;
sum
+= *temp++;
}
return 0;
}
|
The above is my original thinking that fails to work.
I think argument must be array of argc of pointer to integer. So following is the updated code:
#include
<iostream>
int main(int n, int* argv[]) {
std::cout << n << std::endl; //print the number of the arguments passed
int** temp = argv;
int sum = 0;
int i = 0;
while (*temp != NULL) {
std::cout << i++ << ':' << **temp << std::endl;
if (*temp != argv[0])
sum
+= **temp;
++temp;
}
std::cout << "The sum of all integered entered is " << sum << std::endl;
return 0;
}
|
After compiling the code with GCC, I enter ./a.out 1 2 3, and I get
The sum of all integered entered is 1220018326
I know it is far from perfect but it is better than the first one.
I think temp(or argv) is degraded to pointer to a pointer to an integer.
So **temp should be an integer.
Why the print of **temp looks like a pointer?
How can I correctly send actual parameters of integers to main to calculate the sum?