I understand that command line arguments are pointed by the string pointers in the argv [] array. i.e. argv [0] contains a pointer to the name of the program and argv [1] a pointer to the very first command line argument.
But I noticed a very different application of argv on the internet and is written below. I have compiled it successfully and it print out the second arguments third character.
#include <stdio.h>
int main(int argc , char *argv []) {
printf("%c\n", argv [1][2]);
return 0; }
I have two question arising from this use.
What is the true dimension of argv? does it stop at two or is there more?
I have noticed it the code that the programer has used %c to access and print the pointed content. Now, we can always parse a pointer (a string pointer) to %s and expect it to print out the set of chars untill null terminator.
upto the best of my understanding %c can only be used if the array it self contains the character.
i.e.
char yadhavan [] = yadhavan is a boy;
printf ("%c", yadhavan [3]);
Could someone please explain how %c has been used with a pointer array?
A little more explanation is always more than welcome!
argv is of type char*[] and holds several strings(command line arguments).
argv[i] is of type char* and holds a string.
argv[i][j] is of type char and holds a character.
What is the true dimension of argv? Does it stop at two or is there more?
It depends on how many command line arguments there are.
Could someone please explain how %c has been used with a pointer array?
One can declare char pointers and make them point to strings or just use a char array and hold the string:
char* str="string";
Or
char str[]="string";
In both of these ways it is possible to refer a character using:
printf("%c",str[3]);
argv is actually an array of char*. So, it is possible to refer a single character from it.
What is the true dimension of argv? does it stop at two or is there more?
argc tells you the argument count (or the dimension of argv as you put it). In other words, the number of strings in argv is equal to argc. So, argv can contain more than two strings if multiple arguments are provided. For example, if I were to execute some command like
$ foo file1 file2 ...
argv would look like
argv[0] = "foo\0"
argv[1] = "file1\0"
argv[2] = "file2\0"
...
See this other answer for more details on argc vs argv.
Could someone please explain how %c has been used with a pointer array?
First, %s is used for printing strings. %c is used for printing a single character. Second, argv is an array of strings, and a string is simply an array of characters (char). So, argv is really an array of arrays of chars. So, when you see
printf("%c\n", argv[1][2]);
the code is printing out the third character of the second argument in argv. So, if I were to execute the command
$ foo bar
argc and argv would look like
argc = 2
argv[0] = "foo\0"
argv[1] = "bar\0"
argv[1][0] = 'b'
argv[1][1] = 'a'
argv[1][2] = 'r'
argv[1][3] = '\0' // null terminator
char *argv [] is array of pointers and this acts as a two dimention array, it can't contains more than 2D. So the data in 'argv' is very similar to 2D, but limitations are not specified. You can check in the below link:Limit on the number of arguments to main in C
#include <stdio.h>
int main(int argc , char *argv []) {
printf("%c\n", argv [1][2]);
return 0; }
Here char *argv [] is very similar to
Char argv[][] //with no argument limitation.
Related
As a C newbie, I have trouble to understand the following:
int main(int argc, char *argv[]) {
char **inputs = argv + 1;
char **inputs is a pointer to char *argv[] which is also a pointer, right? But why I have to add the "+1" at the end? Will this be an extra space for the '\0' character?
argv[0], or the first argument, is the string holding the name of your program.
argv[0] is the program you're currently running
argv[1+] are the arguments passed to the program
Perhaps not the best reference: https://www.gnu.org/software/gawk/manual/html_node/ARGC-and-ARGV.html
This is just to ignore the first entry which holds the path name that invoked the program. There is always at least one argument passed to main and this is it. Try passing some arguments yourself and print them..you'll get a better idea :)
To explain the "+1" in this context, we are doing pointer arithmetic. This is saying that you want the next memory address after whatever argv points to. Since argv points to the first address in an array of strings (char* in C), then the next memory address is guaranteed to be the second element in the sequence (arrays are laid out contiguously in memory). Thus, argv + 1 is equivalent to saying &argv[1].
As stated before, the first element in argv is just the program name. So you want everything after that for program inputs
K&R says the following about command line arguments:
The first [command line argument] conventionally called argc (for argument count) is the number of command-line arguments the program was invoked with; the second (argv, for argument vector) is a pointer to an array of character strings that contain the arguments, one per string.
As shown above, the second argument is described as a pointer to an array of strings. Just to clarify, is this saying that the second argument is a pointer to a single array that has multiple strings stored in it?
Wouldn't the syntax just be: main (int argc, char argv)
but the syntax is main (int argc, char *argv[])
The parameter syntax looks more like an array of pointers, where each element points to string constants or the first elements of strings in another array.
The loop construct to print what these pointers point at look more like what I just described:
for(i = 1; i < argc; i++)
printf("%s\n", argv[i])
Is the argument an array of pointers? If so, What do the elements actually point to? If it's not, what is the parameter?
In C, a "string" is actually char[].
Also, array (of any base type) in function signature is fully equivalent to pointer to the first element.
Each argument is a string, i.e. a char[], or char*.
An array of strings is char *[], or char**.
Therefore K&R are right, and the signature is what it should be.
BTW, argv[0] is typically the file name of the program and is not interesting unless you have multiple links to the same executable and are doing different things depending on the name by which your program was called. You can also use it for user feedback, such as usage instructions.
This question already has answers here:
What does int argc, char *argv[] mean?
(12 answers)
Closed 9 years ago.
i am really confused regarding this main function,
int main( int argc, char *argv[] ) {
/*statements*/
}
specifically the
char *argv[ ].
What does that represent exactly? i know that it is a pointer to an array of characters, but how is that array created and how does it work exactly? also is that char array the same as a string, since strings are an array or char?
It is a Command line argument.
You can just pass some values during execution of the program like below.
#include<stdio.h>
int main(int count,char *argv[]){
int i=0;
for(i=0;i<count;i++)
printf("\n%s",argv[i]);
return 0;
}
//save file as arg.c
In command line
C:\tc\bin>arg c JS
Output:
*c*
*JS*
It points to the parameters that are passed to your program when you launch it.
Ex:
./a.out toto tata
printf("argv[0]: %s, argv[1]: %s, argv[2]: %s, argv[3]: %s", argv[0], argv[1], argv[2], argv[3]);
Output:
argv[0]: ./a.out , argv[1]: toto, argv[2]: tata, argv[3]: (null)
argc is the number of arguments stored in argv.
You don't have to care about who created it, as it's part of the C standard. Search information about _start function if you really want to know.
argv is an array of string, and each individual string are each selfs arrays of char.
Some time you will see argv noted like this:**argv or argv[][].
char *argv[] is syntactic sugar for char **argv. argv is simply an array of pointers to null-terminated strings. The operating system creates the array for you before invoking your main() function.
int argc = Number of arguments/parameters when running the program (including program name)
char *argv[] = Arguments as an array of "strings" when running the program. This is how I think of it.
Example:
C:\> echo hello world
argc = 3
argv[0] = echo
argv[1] = hello
argv[2] = world
It points to the parameters passed by executing the java file. If you have a class called MyClass with a main method, by calling java myclass a b, you will have a and b in this array. Also in c or c++ calling myCommand a b...
The crucial facts is that it's an array of pointers to characters not a pointer to an array. So you have several pointers to characters, one per "word" in the program's argument list.
char *argv[] is the same as char **argv and argv[0] to argv[argvc-1] are pointers to C style strings(which are NULL terminated). The draft C99 standard actually provides a nice explanation for how it works and what the contents should be, from section 5.1.2.2.1 Program startup paragraph 2 says:
If they are declared, the parameters to the main function shall obey the following
constraints:
— The value of argc shall be nonnegative.
— argv[argc] shall be a null pointer.
— If the value of argc is greater than zero, the array members argv[0] through
argv[argc-1] inclusive shall contain pointers to strings, which are given
implementation-defined values by the host environment prior to program startup. The
intent is to supply to the program information determined prior to program startup
from elsewhere in the hosted environment. If the host environment is not capable of
supplying strings with letters in both uppercase and lowercase, the implementation
shall ensure that the strings are received in lowercase.
— If the value of argc is greater than zero, the string pointed to by argv[0]
represents the program name; argv[0][0] shall be the null character if the
program name is not available from the host environment. If the value of argc is
greater than one, the strings pointed to by argv[1] through argv[argc-1]
represent the program parameters.
— The parameters argc and argv and the strings pointed to by the argv array shall
be modifiable by the program, and retain their last-stored values between program
startup and program termination.
As far as I know, an array like
int example[10]
Is nothing else than a pointer to the first element in this array.
char* argv[]
Is an array of pointers; so that should be pointers which point to other pointers.
I have following problem now:
int main(int argc, char* argv[])
{
double ptrarg2=argv[2][1];
printf("beginletter=%c\nbeginpos=%d\n",&ptrarg2, ptrarg2);
return 0;
}
I am starting the program with ./program test and expecting the output to be:
beginletter=c
beginpos=123213123
While 123213123 should be the adress where the c is actually stored.
I am actually getting:
beginletter=
beginpos=0
what am I doing wrong? Thank you in advance!
It looks like argv[0] is going to be "./program", argv[1] is going to be "test", and argv[2] is going to be undefined or NULL because you don't have three arguments. The value of argc should tell you how many items there are in argv[]. My guess in this case is that the answer will be 2, and therefore only the first two (argv[0] and argv[1]) are valid.
There are several other strange things going on here. ptrarg2 is declared as a double, not as a char; the behavior here would be to convert the character to its floating point numeric equivalent and store that. Perhaps you meant ptrarg2 to be a char?
Next up, the printf() doesn't correspond very well to its additional arguments. &ptrarg2 is a double *, but you're assigning it to a %c (character) field, not a %p (pointer) field. ptrarg2 is a double, but you're assigning it to a %d (decimal number) field, not a %lf (long float, aka double) field. printf will happily try and print out values even when your types don't match, but they will be wrong, and crashing is quite possible.
&ptrarg2 is the address of the local variable, which is not the address that you are expecting. Just use argv[1][0] and argv[1]. argv[1][0] will give you the first character of the first argument, and argv[1] will give you the pointer to the first argument.
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("beginletter=%c\nbeginpos=%p\n",argv[1][0], argv[1]);
return 0;
}
I was confused by a line of code I found in a tutorial on C. Here is the code:
int main(int argc, char *argv[]){
...
char **inputs = argv+1; // This is the confusing line
...
return 0;
}
I can't understand how can you assign an array to a pointer like that. I would be glad if someone could clarify this for me. Thanks ahead!
Say you execute a program like this
C:\Temp>myprog.exe hello world
the operating system takes these strings and puts them together, in an array of null-terminating strings:
{ "myprog.exe", "hello", "world", NULL }
Then it calls main() and passes it the number of strings (3) as argc and a pointer to the first string in this array. this pointer is calles argv, and is of type char** (char* argv[] is just a syntactic convenience, semantically equivalent inside function signatures)
but you want inputs to hold only the string "hello" and "world", so you takes this pointer, argc, and point to the next element - add one to it:
char **inputs = argv+1;
now inputs points toward { "hello", "world", NULL } .
argv is an array pointers to strings, last pointer is null.
Suppose your executable name is exe and you run it like:
$ exe fist second
then argv is:
+----------+
argv---►| "exe" |
+----------+
argv + 1---►| "first" |
+----------+
argv + 2---►| "second" |
+----------+
argv + 3---►| null |
+----------+
* Notice last is null.
So char** input = argv + 1 points to "first" string that is first input argument.
if your prints argv[0] with %s output will be "exe" that is your executable name and if you prints input[0] with %s output will be "fisrt" string.
Note: even if you don't pass any argument intput will point to NULL (valid address).
(purpose of this is to point to input arguments strings, or say skip program name "exe")
My following code example, and its set of outputs will help you to understand.
code.c:
#include<stdio.h>
int main(int argc, char* argv[]){
char** input = argv + 1;
while(*input) /* run untill input-->null */
printf("%s \n", *input++);
return 1;
}
outputs:
~$ gcc code.c -Wall -pedantic -o exe
~$ ./exe
~$ ./exe first
first
~$ ./exe first second
first
second
Array Name is a constant pointer to the first element of array
MORE:-
http://forum.allaboutcircuits.com/showthread.php?t=56256
Arrays used in function arguments are always converted to pointers.
So char *argv[] is the same as char **argv.
argv[0] contains the program name (or the name used to invoke the program, in the case of a multiply-linked file), so argv+1 is just the program's arguments.
argv is not an array in this context; it is a pointer value. In the context of a function parameter declaration, T a[N] and T a[] are equivalent to T *a; in all three declare a as a pointer to T.
However, it would still be possible to make the assignment even if argv were an array. Unless it is the operand of the sizeof or unary & operators, an expression of type "N-element array of T" is converted ("decays") to an expression of type "pointer to T", and the value of the expression is the address of the first element of the array.
Notice that
char *argv[]
Is an array of pointers. An array declaration, is a pointer itself, argv is a pointer. Since here we have an array of pointers, argv is a pointer to a pointer, just like char **inputs, thus
char **inputs = argv+1;
Is just saying inputs is equal to the pointer argv plus one and since argv+1 is also a pointer, then you have a pointer to a pointer.