Argc argv c что это
Перейти к содержимому

Argc argv c что это

  • автор:

Параметры функции main (argc, argv)

При создании консольного приложения в языке программирования С++, автоматически создается строка очень похожая на эту:

int main(int argc, char* argv[]) // параметры функции main()

Эта строка — заголовок главной функции main() , в скобочках объявлены параметры argс и argv. Так вот, если программу запускать через командную строку, то существует возможность передать какую-либо информацию этой программе, для этого и существуют параметры argc и argv[] . Параметр argc имеет тип данных int , и содержит количество параметров, передаваемых в функцию main . Причем argc всегда не меньше 1, даже когда мы не передаем никакой информации, так как первым параметром считается имя функции. Параметр argv[] это массив указателей на строки. Через командную строку можно передать только данные строкового типа. Указатели и строки — это две большие темы, под которые созданы отдельные разделы. Так вот именно через параметр argv[] и передается какая-либо информация. Разработаем программу, которую будем запускать через командную строку Windows, и передавать ей некоторую информацию.

// argc_argv.cpp: определяет точку входа для консольного приложения. #include "stdafx.h" #include using namespace std; int main(int argc, char* argv[]) < if (argc >1)// если передаем аргументы, то argc будет больше 1(в зависимости от кол-ва аргументов) < cout else < cout system("pause"); return 0; >
// argc_argv.cpp: определяет точку входа для консольного приложения. #include using namespace std; int main(int argc, char* argv[]) < if (argc >1)// если передаем аргументы, то argc будет больше 1(в зависимости от кол-ва аргументов) < cout else < cout return 0; >

После того как отладили программу, открываем командную строку Windows и перетаскиваем в окно командной строки экзэшник нашей программы, в командной строке отобразится полный путь к программе(но можно прописать путь к программе в ручную), после этого можно нажимать ENTER и программа запустится (см. Рисунок 1).

Аргументы функции main()

Рисунок 1 — Параметры функции main

Так как мы просто запустили программу и не передавали ей никаких аргументов, появилось сообщение Not arguments . На рисунке 2 изображён запуск этой же программы через командную строку, но уже с передачей ей аргумента Open .

Аргументы функции main()

Рисунок 2 — Параметры функции main

Аргументом является слово Open , как видно из рисунка, это слово появилось на экране. Передавать можно несколько параметров сразу, отделяя их между собой запятой. Если необходимо передать параметр состоящий из нескольких слов, то их необходимо взять в двойные кавычки, и тогда эти слова будут считаться как один параметр. Например, на рисунке изображен запуск программы, с передачей ей аргумента, состоящего из двух слов — It work .

Аргументы функции main()

Рисунок 3 — Параметры функции main

А если убрать кавычки. То увидим только слово It . Если не планируется передавать какую-либо информацию при запуске программы, то можно удалить аргументы в функции main() , также можно менять имена данных аргументов. Иногда встречается модификации параметров argc и argv[] , но это все зависит от типа создаваемого приложения или от среды разработки.

К сожалению, для данной темы пока нет подходящих задач. Если у вас есть таковые на примете, отправте их по адресу: admin@cppstudio.com. Мы их опубликуем!

Как работают argc и argv

Помимо чистой теории из С стандарта, стоит упомянуть как на практике с этими параметрами можно работать, к примеру, argv это просто массив С строк, который вы можете передать в execv() на Unix при создании нового процесса и argv[0] для своих нужд можно задать или чтобы и на Windows можно было произвольные Unicode аргументы принимать, то переносимый код должен аналог boost::nowide::args(argc, argv) вызвать (который GetCommandLineW() , CommandLineToArgvW() вызывает, чтобы восстановить аргументы на Винде).

23 фев 2017 в 10:54
. Или (чтобы ответить «как работают») пример как в памяти аргументы могут располагаться
23 фев 2017 в 10:54

@jfs: Это уже вопрос к автору вопроса: без уточнений — это вопрос о работе с параметрами на принимающей стороне. Никакой разницы между «теорией из стандарта» и «практикой» в данном случае нет. Никакой другой «практики» тут нет и быть не может. Ссылка, которую вы привели, посвящена совсем другой теме: передаче environment через расширенные параметры main в POSIX. При чем здесь это — не ясно. К тому же рассказы о том, как могут располагаться такие аргументы в памяти — это примерно то же самое, что и рассказы о том, какие числа может генерировать rand() .

23 фев 2017 в 15:40

Попробуйте передать консольному приложению через argv имя файла с Unicode символами, которые в текущей code page не представимы на Windows, и мы посмотрим, есть ли разница между теорией и практикой. Вопрос явный не что стандарт разрешает, а «как работают». Считать что мира вне стандарта не существует и отождествлять его с rand() это убого: все абстракции ущербны (all abstractions leak), поэтому видеть не только саму абстракцию, но также как она реализована (хотя бы один этаж вниз) или хотя бы как практические проблемы обойти является полезным. И смотрите внимательней, в коде argv присутствует

C: переменные argc и argv

Для работы с аргументами – в C используются две специальные переменные – argc и argv .

  • argc – argument count, или “счётчик аргументов”;
  • argv – argument vector, или “вектор аргументов”.

Использовать их очень просто.

Создадим такой пример:

#include int main (int argc, char *argv[]) < int count; if (argc >1) < printf ("Total arguments: %dn", argc); for (count = 0; count < argc; count++) < printf ("argv[%d] = %sn", count, argv[count]); >> else < printf ("No arguments passed.n"); >return 0; >
$ gcc argc_argv.c -o argc_argv

Запускаем без аргументов:

$ ./argc_argv No arguments passed.

И с тремя аргументами:

$ ./argc_argv one two three Total arguments: 4 argv[0] = ./argc_argv argv[1] = one argv[2] = two argv[3] = three

What does int argc, char *argv[] mean?

If your program is going to ignore command line arguments, then what you write is fine. If your program needs to process command line arguments, then the IDE is doing it right.

Jun 11, 2010 at 15:57

11 Answers 11

argv and argc are how command line arguments are passed to main() in C and C++.

argc will be the number of strings pointed to by argv . This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array.

The variables are named argc (argument count) and argv (argument vector) by convention, but they can be given any valid identifier: int main(int num_args, char** arg_strings) is equally valid.

They can also be omitted entirely, yielding int main() , if you do not intend to process command line arguments.

Try the following program:

#include int main(int argc, char** argv) < std::cout > 

Running it with ./test a1 b2 c3 will output

Have 4 arguments: ./test a1 b2 c3 

answered Jun 11, 2010 at 15:47
user229044 ♦ user229044
234k 41 41 gold badges 332 332 silver badges 339 339 bronze badges

Thought I should add, this is the same in most systems out there, although they’re abstracted some times. For instance, in Pascal/Delphi/Lazarus, you get; ParamStr and ParamCount (if memory serves me right). My point is, when you (if ever) write native applications in other languages/oses, there’s a good chance the above is defined for you to use, and, they work perfectly the same (count/string list) in all systems which support them.

Oct 8, 2010 at 15:59

But then again, if argc is 0 and argv NULL, then surely argv[argc] = *(NULL + 0) = *NULL = NULL = 0 , right?

Jan 11, 2014 at 21:11

@EmilVikström No, that’s a serious error that probably results in a segfault. *NULL is definitely not equal to NULL .

Jan 12, 2014 at 1:42

@EmilVikström You could do for (char **arg = argv; *arg; arg++) < printf("\t%s\n", *arg);>The *arg in the for loop insinuates *arg != NULL I believe (i.e. while *arg is true).

Sep 25, 2014 at 16:20

argc is the number of arguments being passed into your program from the command line and argv is the array of arguments.

You can loop through the arguments knowing the number of them like:

for(int i = 0; i < argc; i++) < // argv[i] is the argument at index i >

30.8k 22 22 gold badges 106 106 silver badges 131 131 bronze badges
answered Jun 11, 2010 at 15:47
John Boker John Boker
82.8k 17 17 gold badges 97 97 silver badges 130 130 bronze badges

Suppose you run your program thus (using sh syntax):

myprog arg1 arg2 'arg 3' 

If you declared your main as int main(int argc, char *argv[]) , then (in most environments), your main() will be called as if like:

p = < "myprog", "arg1", "arg2", "arg 3", NULL >; exit(main(4, p)); 

However, if you declared your main as int main() , it will be called something like

exit(main()); 

and you don’t get the arguments passed.

Two additional things to note:

  1. These are the only two standard-mandated signatures for main . If a particular platform accepts extra arguments or a different return type, then that’s an extension and should not be relied upon in a portable program.
  2. *argv[] and **argv are exactly equivalent, so you can write int main(int argc, char *argv[]) as int main(int argc, char **argv) .

answered Aug 20, 2015 at 19:01
Toby Speight Toby Speight
28.3k 48 48 gold badges 66 66 silver badges 103 103 bronze badges

If we’re being technical, basic.start.main/2 explicitly allows implementation-defined additional versions of main() , provided that the implementation provides the two predefined versions. So, they’re not exactly non-conforming. The most common one is envp , which is so well-known in both C and C++ that it’s literally the very first entry in section J.5 (Common extensions) of the C standard.

Jan 22, 2017 at 22:40
Thanks for the nice pedantry @Justin. Answer updated to be more correct.
Jan 23, 2017 at 12:34

Is the last element of argv always NULL ? I’m reading some code where argv[1] is called without checking if argc > 1 , and the person who wrote the code clearly expected to either have a correct value, or NULL .

Jun 20, 2022 at 3:39
@user276648, yes — The value of argv[argc] shall be 0 .
Jun 20, 2022 at 7:37

int main(); 

This is a simple declaration. It cannot take any command line arguments.

int main(int argc, char* argv[]); 

This declaration is used when your program must take command-line arguments. When run like such:

myprogram arg1 arg2 arg3 

argc , or Argument Count, will be set to 4 (four arguments), and argv , or Argument Vectors, will be populated with string pointers to «myprogram», «arg1», «arg2», and «arg3». The program invocation ( myprogram ) is included in the arguments!

Alternatively, you could use:

int main(int argc, char** argv); 

This is also valid.

There is another parameter you can add:

int main (int argc, char *argv[], char *envp[]) 

The envp parameter also contains environment variables. Each entry follows this format:

VARIABLENAME=VariableValue 
SHELL=/bin/bash 

The environment variables list is null-terminated.

IMPORTANT: DO NOT use any argv or envp values directly in calls to system() ! This is a huge security hole as malicious users could set environment variables to command-line commands and (potentially) cause massive damage. In general, just don’t use system() . There is almost always a better solution implemented through C libraries.

answered Jan 14, 2018 at 19:33
1,448 1 1 gold badge 16 16 silver badges 24 24 bronze badges

Lets consider the declaration:

int main (int argc, char *argv[]) 

In the above declaration, the type of the second parameter named argv is actually a char** . That is, argv is a pointer to a pointer to a char . This is because a char* [] decays to a char** due to type decay. For example, the below given declarations are equivalent:

int main (int argc, char *argv[]); //first declaration int main (int argc, char **argv); //RE-DECLARATION. Equivalent to the above declaration 

In other words, argv is a pointer that points to the first element of an array with elements of type char* . Moreover, each elements argv[i] of the array(with elements of type char* ) itself point to a character which is the start of a null terminated character string. That is, each element argv[i] points to the first element of an array with elements of type char (and not const char ). A diagram is given for illustration purposes:

argv and argc

As already said in other answers, this form of declaration of main is used when we want to make use of the command line argument(s).

answered May 11, 2022 at 14:50
user12002570 user12002570
38k 5 5 gold badges 26 26 silver badges 67 67 bronze badges

The parameters to main represent the command line parameters provided to the program when it was started. The argc parameter represents the number of command line arguments, and char *argv[] is an array of strings (character pointers) representing the individual arguments provided on the command line.

12.2k 4 4 gold badges 28 28 silver badges 42 42 bronze badges
answered Jun 11, 2010 at 15:47
BlueMonkMN BlueMonkMN
25.2k 9 9 gold badges 80 80 silver badges 147 147 bronze badges

Argv[] always has argv[arg] as a null pointer. and Argv[0] is always the (full path)/executableName as a nul terminated string

Dec 21, 2014 at 8:09

@user3629249: Not necessarily; argv[0] is whatever the the program launching the C program gave it as argv[0] . In the case of Bash, it is often (maybe always) the pathname of the executable, but Bash is not the only program that executes other programs. It is permissisble, though eccentric, to use: char *args[] = < "cat", "/dev/null", "/etc/passwd", 0 >; execv(«/bin/ls», args); . On many systems, the value seen by the program as argv[0] will be cat , even though the executable is /bin/ls .

Feb 5, 2016 at 3:36

The main function can have two parameters, argc and argv . argc is an integer ( int ) parameter, and it is the number of arguments passed to the program.

The program name is always the first argument, so there will be at least one argument to a program and the minimum value of argc will be one. But if a program has itself two arguments the value of argc will be three.

Parameter argv points to a string array and is called the argument vector. It is a one dimensional string array of function arguments.

12.2k 4 4 gold badges 28 28 silver badges 42 42 bronze badges
answered Jul 21, 2015 at 8:28
219 2 2 silver badges 2 2 bronze badges

The first parameter is the number of arguments provided and the second parameter is a list of strings representing those arguments.

answered Jun 11, 2010 at 15:48
Nick Gerakines Nick Gerakines
1,450 1 1 gold badge 11 11 silver badges 20 20 bronze badges
the first entry in argv[0] is the program name, not an argument
Dec 21, 2014 at 8:10
@user3629249 Program name with program path. 😉
Jul 20, 2018 at 8:10

Command-line Arguments: main( int argc, char * argv[] )

In Unix, when you pass additional arguments to a command, those commands must be passed to the executing process. For example, in calling ls -al , it executes the program ls and passes the string -al as an argument:

% ls content.html index.html primary.0.html % ls -al total 20 drwxr-xr-x 2 dwharder users 4096 Sep 11 16:38 . drwxr-xr-x 6 dwharder users 4096 Sep 11 16:35 .. -rwxr-xr-x 1 dwharder users 117 Sep 11 16:38 content.html -rwxr-xr-x 1 dwharder users 1400 Sep 11 16:37 index.html -rwxr-xr-x 1 dwharder users 532 Sep 11 16:38 primary.0.html % 

The way a running program accesses these additional parameters is that these are passed as parameters to the function main:

int main( int argc, char *argv[] )  

Here argc means argument count and argv means argument vector.

The first argument is the number of parameters passed plus one to include the name of the program that was executed to get those process running. Thus, argc is always greater than zero and argv[0] is the name of the executable (including the path) that was run to begin this process. For example, if we run

#include int main( int argc, char *argv[] )

Here we compile this code and first compile and run it so that the executable name is a.out and then we compile it again and run it so the executable name is arg :

% gcc argument.0.c % ./a.out argv[0]: ./a.out % gcc -o arg argument.0.c % ./arg argv[0]: ./arg % 

If more additional command-line arguments are passed, the string of all characters is parsed and separated into substrings based on a few rules; however, if all the characters are either characters, numbers or spaces, the shell will separate the based on spaces and assign args[1] the address of the first, args[2] the address of the second, and so on.

The following program prints all the arguments:

#include int main( int argc, char *argv[] ) < int i; printf( "argc: %d\n", argc ); printf( "argv[0]: %s\n", argv[0] ); if ( argc == 1 ) < printf( "No arguments were passed.\n" ); >else < printf( "Arguments:\n" ); for ( i = 1; i < argc; ++i ) < printf( " %d. %s\n", i, argv[i] ); >> return 0; > 

Here we execute this program with one and then twelve command-line arguments:

% gcc argument.c % ./a.out first argc: 2 argv[0]: ./a.out Arguments: 1. first % ./a.out first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth argc: 13 argv[0]: ./a.out Arguments: 1. first 2. second 3. third 4. fourth 5. fifth 6. sixth 7. seventh 8. eighth 9. ninth 10. tenth 11. eleventh 12. twelfth % 

For Fun

Now, you may be wondering what actually happens (and if you don't, you're welcome to skip this). First, when the command is executed, the shell parses the command line and separates the individual pieces by a null character \0 . For example, the execution of

% ./a.out first second third fourth fifth 

has the shell generate the string ./a.out☐first☐second☐third☐fourth☐fifth☐ where the box represents the null character. Next, memory for an array of six ( argc ) pointers is allocated and these six pointers are assigned the first character of each of the strings into which the command line was parsed. Finally, memory is allocated for the stack and using 8-byte alignment, the two arguments are placed into the stack. This is shown in Figure 1.

The result of calling ./a.out first second third fourth fifth on the command line

Figure 1. The result of calling ./a.out first second third fourth fifth on the command line.

Further Fun

In Unix, the shell does further processing of the command. For example, if it finds wild cards that indicate files in the current directory, it will attempt to expand those wild cards. These include ? for one unknown character and * for any number of characters.

For example, the following examines the file in the current directory:

% ls a.out argument.0.c argument.1.c content.html images index.html primary.0.html src % ./a.out * argc: 9 argv[0]: ./a.out Arguments: 1. a.out 2. argument.0.c 3. argument.1.c 4. content.html 5. images 6. index.html 7. primary.0.html 8. src % ./a.out *.html argc: 4 argv[0]: ./a.out Arguments: 1. content.html 2. index.html 3. primary.0.html % ./a.out argument. c argc: 3 argv[0]: ./a.out Arguments: 1. argument.0.c 2. argument.1.c 

Similarly, you can tell the command line to treat spaces as part of one string or ignore wildcards by either using the backslash before the space or wildcard or surrounding the string by single or double quotes.

% ./a.out hi\ there\? argc: 2 argv[0]: ./a.out Arguments: 1. hi there? % ./a.out "hi there?" argc: 2 argv[0]: ./a.out Arguments: 1. hi there? % ./a.out 'hi there?' argc: 2 argv[0]: ./a.out Arguments: 1. hi there? % 

Finally, if you surround text with backticks, it will execute that first and then replace that with the output of the command:

% ./a.out `ls *.c` argc: 4 argv[0]: ./a.out Arguments: 2. argument.0.c 3. argument.1.c % 

./a.out ls -al

Guess what happens if you enter .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *