This is more of a conceptual question at this point rather than a practical one but it is really bothering me.
Let us say I have a c program called "test.c" and I want to find the number of spaces in array there are for a word the user types in as an argument. For example "./test.c test_run" should print 9 because there are 8 characters and then one for the null terminating character. When I try to use sizeof on argv though I am having some trouble.
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 chose a char array. In C, the size of a char is 1 byte. If I chose int, this number would 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 output:
argv[1] has the value: Hello_SO strlen of argv[1] is: 8 sizeof of argv[1] is: 4 The string length makes sense because it should be 9 but minus the "\0" makes 8.
However I do not understand why sizeof is returning 4 (the size of the pointer). I understand that *argv[] can be thought of as **argv. But I accounted for this already. In my first example i print "buf" but here i print "argv[1]". I know I could easily get the answer by using strlen but as I said earlier this is just conceptual at this point.
argv[1]has typechar *, sosizeof argv[1]meanssizeof(char *). That's what sizeof does.buf10is an array type, not a pointer.%zuto printsize_tvalues... Okay, I misunderstood your question initially. Perhaps a more illuminating example:char *fubar = "hello world";What kind of value do you expectsizeof NULLto produce, compared tosizeof fubar? Shouldsizeofattempt to follow the pointer to find out the size of that which is pointed at? If so, then the first example is surely invalid, right?