What's the difference between:
int main(int argc, char* argv[])
and
int main(int argc, string argv[])
How does char* argv[] behave when compared to string argv[] and why do we need string argv[] ?
Why is string argv[] not a pointer variable in the argument here:
int main(int argc, string argv[])
{
string str = argv[1];
printf("%s\n",str);
}
where as if I use char I must use a pointer:
int main(int argc, char* argv[])
{
string str = argv[1];
printf("%s\n",str);
}
I found out what char* argv[] means and string argv[] means. They both mean the same.
To illustrate why, Let's look into the below example:
string S = "Hi!"
what exactly happens in the background while using strings?
Let's say for example:
char* S = "Hi!";
Here we create a pointer variable S that's gonna store the address of a char. "Hi!" is stored somewhere in memory that we do not know. The address of the first character of "Hi!" is stored in S(which is the same as saying variable S points to H). In simple terms, S is storing an address(the address of character 'H'). Thus we can access all the elements one by one till we find '/0' since we know that a string ends when it finds a '/0'
If I abstract away all the details the above code can also be written as:
string S = "Hi!"
which is the same as saying char* S = "Hi!"
What if I wanna access each character then:
printf("%c", *(S)); // dereferencing the first character which is H
printf("%c", *(S+1)); // dereferencing the second character which is i
printf("%c", *(S+2)); // dereferencing the third character which is !
If I were to access each character in strings then I would say:
printf("%c", S[0]);
printf("%c", S[1]);
printf("%c", S[2]);
where both methods do the same thing. The latter is more readable than the former which is why it is commonly used.
So we can conclude that char* S is the same as string S. Since when we use strings, in the background, it uses a char pointer to access each element of the string that's stored in memory. They both do the same thing. Using String abstracts all the details.
This solves my doubt as to why char argv[] the same as string argv[]. String argv[] does the same thing as char argv[] does but it hides the implementation and makes it easier for readability.