I have code like this to store argv
to a dynamically allocated int
array:
int *data; // pointer to array of integer numbers
int size; // size of data array
int main(int argc, char* argv[]) {
// initialize array data
size=argc;
printf("%dSize=\n",size);
printf("%d\n",argc);
data=(int*)calloc(size,sizeof(int));
int i=0;
for (i=1;i<size;i++)
{
data[i]=argv[i];
printf("%d\n",data[i]);
}
for (i=1;i<argc;i++)
{
printf("%d\n",argv[i]);
}
return 0;
}
When I run in command line:
./sumprime 5 1 2 3 4
It prints:
6Size=
6
15311660
15311662
15311664
15311666
15311668
15311660
15311662
15311664
15311666
15311668
Not an array of 5 1 2 3 4
as I expected. How can I store an int
array from argv
and then print it out?
Should be:
data[i]=atoi(argv[i]);
Remember command line argument are strings. So even though you pass an integer in the command line its a string that needs to be converted to an integer.