Hi,
Thank you everyone for the help.
Robertlzw, Disch, you are right, I was using gcc and should of been using g++, hence why it compiled.
I see from this website's tutorial section:
NOTE: The elements field within brackets [] which represents the number of elements the array is going to hold, must be a constant value, since arrays are blocks of non-dynamic memory whose size must be determined before execution. In order to create arrays with a variable length dynamic memory is needed, which is explained later in these tutorials.
|
krishnendu, thank you for your time, however I was doing this as an exercise on pointers
Turns out, I had number of elements for my array wrong, it should not be argc - 1, I mistakenly thought it was # of elements starting at 0 while I should of just passed agrc.
As for why my code didn't work, I had (*argt)++ which increased the value of the first array elemnt instead of increasing the pointer position of the argv array.
Here is my working code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
#include <cstdlib>
using namespace std;
template <typename T>
T sum(T a[], int size){
T result = 0;
for(int i = 0; i < size; i++)
result += a[i];
return result;
}
int main(int argc, char *argv[]) {
int intarray[argc];
int *ia = intarray;
int result=0;
char **argt = argv;
while(*argt){
*ia=atoi(*argt);
ia++;
*argt++;
}
result = sum(intarray, argc);
cout << result << endl;
cout << "Yes" << endl;
return 0;
}
|
Thank you everyone!