This is more of a conceptual question at the moment than a practical one, but it really bothers me.
Say I have a c program called "test.c" and I want to find the number of spaces in the array for the word that the user enters as an argument. For example, "./test.c test_run" should print 9 because there are 8 characters, and then one for the zero termination character. When I try to use sizeof for argv, although I am having some problems.
int main(int argc, char *argv[]) { char buf10[10]; printf("The size of buf10 is: %i.\n", sizeof(buf10)); return 0; }
Prints the result: "The size of buf10 is: 10. ". This makes sense because I selected a char array. In C, the size of a char is 1 byte. If I chose int, this number will be 4.
Now my question is: why can't I do this with argv?
int main(int argc, char *argv[]) { printf("argv[1] has the value: %s\n", argv[1]); printf("strlen of argv[1] is: %i\n", strlen(argv[1])); printf("sizeof of argv[1] is: %i\n", sizeof(argv[1])); return 0; }
Ran with "./test Hello_SO" gives the result:
argv[1] has the value: Hello_SO strlen of argv[1] is: 8 sizeof of argv[1] is: 4
The length of the line makes sense, since it should be 9, but minus "\ 0" is 8.
However, I do not understand why sizeof returns 4 (pointer size). I understand that * argv [] can be thought of as ** argv. But I have explained it already. In my first example, I type "buf", but here I type "argv [1]". I know that I could easily get the answer using strlen, but as I said earlier, this is just conceptual at the moment.