Derek Halden
Derek Halden

Reputation: 2323

Homework: Why is argv[2] defined?

I am getting a weird string for my argv[2], when I run this program without any inputs. Why isn't argv[2] undefined? TERM_PROGRAM=Apple_T <- That's what I get. I'm wondering if this has something to do with running it on a mac?

if(argv[2]) {
    sscanf(argv[2], "%lf", &argWind);
    sscanf(argv[2], "%20s",  str);
    sprintf(str2, "%lf", argWind);
    printf("String: %s, %lf", str, argWind);
    int len;
    len = strlen(str);
    str2[len] = '\0';

    if(strcmp(str, str2)){
        printf("\nError: you entered a non-numeric entry for wind speed\n");
        return 0;
    }
} 

Upvotes: 0

Views: 293

Answers (3)

Xiaofei HAN
Xiaofei HAN

Reputation: 159

you'd better check "argc" firstly, then you can choose to use the valid "argv"

Upvotes: 1

lqhcpsgbl
lqhcpsgbl

Reputation: 3782

argv[2] is the third parameter of the command line like this code, argc is the number of parameters:

int main(int argc, char const *argv[])
{
  int i = 0;
  for (; i < argc; ++i)
  {
     printf("%d -> %s\n", i, argv[i]); 
  }
  return 0;
}

See the process:

F:\so>tcc test.c

F:\so>test.exe a b c
0 -> test.exe
1 -> a
2 -> b
3 -> c

test.exe is the first, a is the second, b is third, c is the fourth. If you run test.exe whitout other parameters, it will say argv[2] means b here is not defined.

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 224934

Undefined behaviour is undefined. Anything could happen. In this case it looks like you're running past argv and into the third (less well known and certainly nonstandard) parameter of main, commonly called envp. Relevant link.

Upvotes: 7

Related Questions