0

I'm new to C and trying to figure out arrays and command line arguments. I have:

int main(int argc, int **argv) {
    int vals[8];
    for(int i = 0;i < 8;i = i + 1) {
        vals[i] = atoi(argv[i]);
        printf("%d", vals[i]);
    }
}

I call it with ./file 1 2 3 4 5 6 7 8 and I would expect it to spit out 12345678, but instead, it spits out 01234567 which to me says that it's just printing the array positions. How do I get to actually print/access the value of vals[i], and/or make sure that the command line value is actually being properly assigned?

Thanks in advance.

5
  • 3
    Use any other example to test your program. Try ./file 8 7 6 5 4 3 2 1. Commented Apr 13, 2017 at 18:35
  • atoi issues 0 for your program name because it failed to convert to integer. Commented Apr 13, 2017 at 18:36
  • Which is why, generally speaking, atoi() is a bad idea and you should use one of the strto___() functions. Commented Apr 13, 2017 at 18:38
  • @JohnHascall /strto[a-z]+/ will also return 0 but set errno in certain implementations Commented Apr 13, 2017 at 18:53
  • argv[0] is the name of the program (./file). atoi() will return 0 when given such a string. Commented Apr 13, 2017 at 23:34

2 Answers 2

2

Start with argv[1] In order to exclude the first element of argv which is the program name. A simple way to do this is to increment argv at the top of the program.

int main(int argc, char **argv) {
    argv++; /* argv[0] is the program name */
    int vals[8];
    for(int i = 0;i < 8;i = i + 1) {
        vals[i] = atoi(argv[i]);
        printf("%d", vals[i]);
    }
}

On a side note, you should check the value of argc prior to accessing elements at index i in argv

Sign up to request clarification or add additional context in comments.

3 Comments

why completely ignoring argc ?
See my edit, please. Furthermore, I think for his particular question, telling him about the possiblity of undefined behavior is out of scope.
It might have worked but, rather than incrementing argv, it would have been better to start the loop with i = 1. And have the loop condition related to argc. Reading from argv[i] if no such argument has been given yields undefined behaviour.
0

argv [0] is the name of the program.

The arguments start at 1. You should also get in the habit of using argc in loops.

 int main(int argc, int *argv[]) 
 {
     for(int i = 1 ; i < argc ; ++ i ) 
     {
       int val = atoi(argv[i]);
       printf("%d", val);
     }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.