Search code examples
carraysnullstrcmp

how i can see if an array with arguments is null in c


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


Solution

  • "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.