-2

i have this code :

  int main(int re, char *args[]){
  int comp=1;
  int j=2;
  int count=0;
 //printf("%d",args[1]);
  while(comp!=0){
       comp=strcmp(args[j],"null");
       j++;
       count++;
  }
}

and i want to see how many string i have in my argument array (args[]), the problem is that a take segmentation fault and i cant find why. When i put NULL instead "null" i get the same result ,segmentation fault. There is a problem with args[j]? or is something else that i dont see? Iam getting out of bounce in my array? i know that the strings begin from args[2] so this is why i put j=2 in the code i put the header file #include to use strcmp

burrito
  • 143
  • 1
  • 2
  • 11
  • 1
    Why are you renaming `argc` to `re`? Also, to check if a pointer is null, use `if (myPointer == NULL) {...}`. And while I'm at it, your `while` loop logic will take you past any eventual arguments, since you only go up and don't stop till you hit 0. – AntonH Nov 23 '17 at 16:14
  • `re` is the size of `args`, so use that to check if you've gone out of bounds – Chris Turner Nov 23 '17 at 16:16
  • 1
    Note that `"null"` is a constant char array containing 5 characters : `'n' 'u' 'l' 'l' '\0'`, and `NULL` is a constant defined in `stdlib.h`. `"null" == NULL` will always be `false` – Hollyol Nov 23 '17 at 16:25

2 Answers2

3

"null" is a string literal with no special meaning, and NULL is a null-pointer (you could just as well write 0 for it), which is what you mean, but comparing it as a string (with strcmp()) doesn't make any sense. You want to know whether the pointer at args[j] is null (and then, it isn't pointing to anything, so it isn't a string).

Although you get passed the number of arguments in the first parameter to main() anyways, which is almost always simpler to use, the C standard guarantees you that argv[argc] is indeed NULL, so your approach works when implemented correctly. Example:

int main(int argc, char **argv)
{
    int i = 0;
    while (argv[i])  // or more explicit while (argv[i] != NULL)
    {
        puts(argv[i++]); // print this argument
    }
}

Relevant passage in the standard (citing N1570 here) is §5.1.2.2.1 p2:

[...]
-- argv[argc] shall be a null pointer.

1

The main function has two parameters,

int main(int argc, char **argv);

argc counts the number of arguments

argv has the arguments as strings in a 2D array.

So, You can just say:

if (argc == 1)
{
   printf("I'm having 0 arguments in Total");
}

The first argc takes up the name of the executable - a.out- . So, if you didn't change the name, a.out is the first argument.

josemartindev
  • 1,413
  • 9
  • 17