I'm reviewing this code which converts the capital letters to lower case and I don't understand why it declares char*argv[]
and later inside the for loop it uses argv[1][i]
as if it were a two-dimensional array.
Any tip is welcomed, thanks.
#include <stdio.h>
int main(int argc, char*argv[]){
if(argc>1) {
int i;
char c;
for(i=1; (c=argv[1][i]) != '\0'; i ){
if('A'<=c && c<='Z')
putchar(c 'a'-'A');
else
putchar(c);
}
putchar('\n');
}
}
CodePudding user response:
argv
is not actually a 2 dimensional array but an array of char *
. Each of those pointers point to a string, each of which is a char
array, so it can be accessed the same way a 2 dimensional array is.
More specifically, each member of argv
is a command line argument passed to the program, with the first member conventionally being the name of the program. Those arguments are strings, and each string is an array of characters. So argv[1][i]
grabs the ith character from the first command line argument.
CodePudding user response:
As it is seen from the declaration of the second parameter in main
char*argv[]
it is an array of pointers of the type char *
.
Pay attention to that function parameters having array types are adjusted by the compiler to pointers to array element types.
So these two declarations of main
int main(int argc, char*argv[]){
and
int main(int argc, char**argv){
are equivalent.
So if you have an array of pointers like for example
char * s[] = { "Hello", "World" };
then this array contains two pointers to first characters of the string literals "Hello"
and "World"
.
So to output elements of the array you can use these nested for loops
for ( size_t i = 0; i < sizeof( s ) / sizeof( *s ) /* == 2 */; i )
{
for ( size_t j = 0; s[i][j] != '\0'; j )
{
putchar( s[i][j] );
}
putchar( ' ' );
}
putchar( '\n' );
To understand the inner loop consider the following code snippet
char *p = "Hello";
for ( size_t i = 0; s[i] != '\0'; i )
{
[utchar( s[i] );
}
putchar( '\n' );
In the first code snippet you have an array of two such pointers.
CodePudding user response:
When you run your code with parameters, they are stored in the char argv array.
This means that the values are stored in a char array (holding a string value)
Each parameter is separated with spaces e.g. a.exe hello.
If you do printf("%s", argv[1]);
You will get the result "hello", the value of argv[1]
is the whole string, if you want to access individual characters of that string you can do it by using multi-array notation argv[1][0]
which will give you the first char, in this case, h