2

I ran the following just for fun, but cannot account for the result. Assume ./test WTF? was run at the command line, and the output produced was WTF? 6 2. Why is there such a vast discrepancy between the reported value of argc (2 - as expected) and strlen(*argv), which came up as 6. I know an array of strings isn't exactly what strlen is looking for, however, I thought the value it produced (if it produced anything) would be reasonably close to argc. Thoughts?

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, char**argv)
{
    for (int i = 1; i < argc; i++)
    {
        for (int j = 0; j < strlen(argv[i]); j++)
        {
            printf("%c", argv[i][j]);

        }
        printf(" ");
    }
    printf("\t%lu\t%d", strlen(*argv), argc);
    printf("\n");
}
Ryan
  • 1,312
  • 3
  • 20
  • 40

2 Answers2

5

Nothing wrong here. The argv array contains two strings -

  1. program name as invoked --> "./test"
  2. "WTF?".

So in your example strlen(argv[0]) will print 6 and strlen(argv[1]) will print 4.

VHS
  • 9,534
  • 3
  • 19
  • 43
  • Correct and understood. What I did not realise I had done with strlen(*argv) was write a synonym for strlen(argv[0]). Thanks for the reply! – Ryan Jul 14 '17 at 19:10
3

For example, if you run gcc -o myprog myprog.c in command line, you will get the followings:

argc
4 
argv[0]
   gcc 
argv[1]
   -o 
argv[2]
   myprog 
argv[3]
   myprog.c

Therefore, for your case you will get 6 (length of ./test for argv[0]) instead of 4 (length of WTF? argv[1]) as you run ./test WTF? in command line.

OmG
  • 18,337
  • 10
  • 57
  • 90