Click here to Skip to main content
15,889,034 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Trying to input the argv command line inputs into an array.
All it's printing out is the memory location and not the argv inputs

What I have tried:

C
#define MAX 12

int main(int argc, char* argv[])
{
  char* argv_inputs[MAX];
  int array_of_ints[MAX];
  int i, size = argc;

  for(i = 2; i <= argc; i++)
  {
    argv_inputs[i] = argv[i];
    printf("%d ", argv_inputs[i]);
  }
Posted
Updated 16-Sep-21 22:58pm
v2

You don't need a copy of the argv input array but have to convert the textual arguments to numbers using atoi - C++ Reference[^] or strtol - C++ Reference[^] :
int main(int argc, char* argv[])
{
    int array_of_ints[MAX];
    int i;
    
    for (i = 1; i < argc && i < MAX; i++)
    {
        array_of_ints[i] = atoi(argv[i]);
        printf("%d ", array_of_ints[i]);
    }
    return 0;
}
Note that the above does not check if the input is a valid number and that I have corrected the loop. With C/C++, arrays start at the index zero and the last item is therefore accessed by size - 1.
[EDIT]
I have also added a check to ensure that no out-of-bound accesses occur.
[/EDIT]
 
Share this answer
 
v2
Comments
CPallini 11-Sep-17 11:01am    
5.Skipping the array item 0 in order to mimic VB? :-)
Jochen Arndt 11-Sep-17 11:27am    
Thank you.

Skipping argv[0] as program path. I was thinking about storing starting at index zero but he has used the same index for both and so I decided to do it too.
The input is an array of pointer-to-char values, and you are assigning them to an array of integers. That won't work: while the pointers are integer values (or long integer values in a 64 bit application, the numbers themselves are meaningless - they are the addresses of the first character in each string, so when you print them you get numbers which make no sense at all.
Try this:
int main(int argc, char* argv[])
    {
    int i;
    for(i = 2; i < argc; i++)
        {
        printf("%s\n", argv[i]);
        }
    }
That will print the inputs.
 
Share this answer
 
v2
Comments
CPallini 11-Sep-17 11:02am    
Hey man, you are going out of bounds. :-)
OriginalGriff 11-Sep-17 11:12am    
Yeah, it shouldn't have the "=" in there. I'll remove it...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900