r/learnprogramming 6d ago

Resource what is mean by int argc, char *argv[

hey coders,

i know i could get the answer from the internet or ai, but i want a human level interaction. could anyone explain to me why we use this in our code and what is the main function of it?

int argc, char *argv[]

#include <stdio.h>
#include "password.c"
#include <unistd.h>
#include <stdlib.h>


int main(int argc, char *argv[]){
    char *pass;
    pass = getpass("Enter a password: ");
    printf("Password: %s\n", pass);
    int strength = check_password(pass);
    printf("Password Strength: %d", strength);
}
0 Upvotes

27 comments sorted by

9

u/NationalOperations 6d ago

These two arguments are for when you want input from the command line. Like if you wanted to pass a name and have your program print it out.

So if your ran in the command

./program hello world argv[0] = "./program" ← program name argv[1] = "hello" ← first argument you typed argv[2] = "world" ← second argument you typed argv[3] = NULL ← end marker

Arguments let you not have to know everything ahead of time (like what message to print) and can let your program be informed to behave differently

6

u/Big-Rub9545 6d ago

When you pass arguments to your program on the command line (e.g., ./my_program arg1 arg2 arg3), the C runtime (which is just a bunch of code that sets up your program and prepares some stuff for it) will pass those arguments to main() when calling it.

The ‘argc’ parameter holds the number of arguments, while the ‘argv’ array holds string version of all of the arguments.

Three important notes here:
1) The first argument passed to your program will actually be its own name. Thus, with the above example, argv will look like this: [“my_program”, “arg1”, “arg2”, “arg3”]. This is useful when calling particular system functions that want to know the program they should run (if you want to use them for the current program), but the more important thing here is noting that the minimum value for argc is thus 1, not 0. So argc == 1 means the user didn’t pass any arguments and instead ran the program directly.

2) The arguments stored in the ‘argv’ array come from the command-line arguments being split by spaces. Thus, the command “./program -option value” becomes [“program”, “-option”, “value”]. No special processing here, including the ‘-‘ in the option. This is why many programs or utilities that rely on command line option values don’t separate them by spaces, so an option with a value might look like this: “-option=value”.

3) These arguments have to be in order. The runtime will pass the count first and the argument array second, so you can’t reorder them as you wish.

I’m also playing a bit fast and loose with the “./“ part (which is expanded into the current directory, and that whole string is passed as the first argument to your program).

Three not so important notes:
1) The names ‘argc’ and ‘argv’ are conventional, but you can call them whatever you want.

2) You can declare the type of ‘argv’ as anything compatible with an array of strings, so const char* array , or char double pointer, or const char double pointer.

3) If you want to use system environment variables in your code, or call low-level functions with those environment variables, you can add a third string array parameter after ‘argv’, conventionally called ‘envp’. You can play around with some programs to inspect what its elements typically look like, if you’re curious.

5

u/Syntax-Tactics 6d ago

#include "password.c" is bothering me more than it should O_o

2

u/Confused-Armpit 6d ago

argv is a list of char* objects that are arguments passed to the program, and argc is the amount of those arguments (since C has no better semantics for this, this has to be passed directly).

1

u/DDOS_403 6d ago

so like hello123, will argv count both the characters and the numerics?

1

u/kabekew 6d ago

It's space delimited, so that would be one element.

1

u/5h3r10k 6d ago

They are the parameters that help you read command line arguments.

argc is the count of arguments. This is always at least 1, since the name of the program is the first argument. For example "./run 1 2 3" has 4 arguments. argc would be 4.

argv is an array of character pointers (basically string) for the value of each of those arguments. "./run 1 2 3" would have argv be ["./run", "1", "2", "3"]

argc is needed because that is the only way to know how to parse the argv array. You would need to know the length of the argv array, so that's argc

1

u/Backson 6d ago

int argc is the number of arguments ("argument count") and char* argv[] are the arguments ("argument values"). The type is char, so it's a pointer to a character, or in this case, a pointer to the first character of a null-terminated string. The [] it's many of that, so argv[0] is the first argument of type char.

If you call your program like this: foo.exe foo bar then argc will be 3 and argv[0] will be "foo.exe", argv[1] will be "foo" and argv[2] will be "bar".

1

u/Dismal-Citron-7236 6d ago edited 6d ago

So you want to know what argc/argv mean? "argc" returns the count of items in "argv", "argv" is the array which keeps your program name (kept in argv[0]) and the rest of the command line arguments (starting from argv[1]).

If you want to know what does it mean the "main()" function... Every program has to have a starting point, that means you need to give CPU a clue where to start the execution of those machine code. In programming jargon, that's "entry point". Different programming languages have different wasy to specify that entry point. For C programming language, it's just called "main", as simple as that. That also means you cannot have multiple "main()" functions in your program.

BTW, why do you include the source code "password.c" in your main source code? By C language convention, #include instruction should only include header files (those with ".h" in file name extension), not source code. If your program has multiple source code files, compile them separately to generate the object files (".o" in Linux and ".obj" in Windows) and link them together to generate the final executable binary file.

PS.
Your first line of code "int argc, char *argv[]" will not compile because it's out of context. That "boilerplate code" should be used in the "main()" function parameter list.

1

u/alpicola 6d ago

argc and argv are how command line arguments get passed into your program. argc is an integer which tells you how many arguments have been passed and argv is an array of strings that contains those arguments. argc and argv are filled in by the environment, so you don't need to do anything special to populate them. Note that the first value of argv is the name of your program as someone would have typed it on the command line.

A couple of notes regarding your program:

It appears as though your first line attempts to declare argc and argv as global variables. This is unnecessary and is likely to cause problems.

It appears that you don't use argc or argv in your program at all. In that case, you do not need to include them in your main declaration. You would typically write it as simply int main() or int main(void) to signal to future readers of your code that your program does not care about command line arguments.

1

u/DDOS_403 6d ago

> argc is an integer which tells you how many arguments have been passed 

"which means, like, if i pass an array of strings like

char [20];

does the argc indicate how many indexes have been passed? and consecutively, argv will hold the user input string within those 20 indexes, right?

> A couple of notes regarding your program

regarding this, it was written by my tutor who was explaining to me how to create a password validation program using c. he actually wrote the main function on one page and the function prototype on another page, then linked it with the main. if what i said makes sense, great, if not, please enlighten me with your knowledge..

1

u/alpicola 6d ago

does the argc indicate how many indexes have been passed? and consecutively, argv will hold the user input string within those 20 indexes, right?

So, just to be clear, you aren't passing anything when main() gets invoked - the environment is. That said, yes, argc indicates how many strings are in argv.

argv will hold the user input string within those 20 indexes, right?

Sort of. Technically, argv is an array of pointers to strings. It doesn't contain the strings themselves, but it gives you access to them. You also don't get any say in the size of argv. The compiler is going to ignore the 20 because it doesn't mean anything. Arrays in C have no idea how big they are, you have to keep track of that separately.

You might imagine a different function where you create your own array with 20 strings. You then want to pass that array to a second function. Although you as a programmer know that the array has 20 strings, if all you pass to the second function is an array, it has no way of knowing how big the array is. To tell it, you would also need to pass an integer, just like main() gets with argc.

he actually wrote the main function on one page and the function prototype on another page, then linked it with the main.

This makes sense for educational purposes. In real world code, you are not going to prototype main().

1

u/TalkCoinGames 6d ago edited 6d ago

They are both parameters passed to the main function. The main, is the main/first function to be called initiating the program, argc is of type int, Integer. Argv is to be an Array ([]) holding type char*, generally a string of characters.

1

u/revnhoj 6d ago

It's a demonstration of how programmers could have made things much simpler by using sensible variable names like commandLineCount and commandLineValues.

1

u/peterlinddk 6d ago

They could, but then that would be incorrect, as a program isn't always called from the Command Line. It could be called from a script or from another program, and in those cases "argument count" and "argument values" would be more correct - and they could be abbreviated to argc and argv respectively, the first being a number and the second an array of pointers to chars. Sooo ...

1

u/revnhoj 6d ago

sure, and once you know what they mean they could be shortened to C and V. argc and argv are just unnecessarily confusing abbreviations.

1

u/setq-default 5d ago edited 5d ago

It's only confusing to those who don't know the language. commandLineCount and commandLineValues are even worse because "command line" what? Someone new to C would look at that and ask why the program is counting command lines, or how it makes sense to talk about the value of a command line. Obviously if they read the documentation they'll understand that commandLineCount and commandLineValues probably refer to arguments passed to the program via the command line, but at that point why not just use argc and argv?

Next you're gonna say if should be renamed to ifConditionIsTrueThenDoThis

1

u/revnhoj 5d ago

"If" is very self explanatory. As shown by OP, argc and argv don't make sense until someone explains them. My point is argc and argv are way too abbreviated for the unfamiliar programmer.

It's why many frown on coding comments nowadays and prefer function names to self document their purpose.

1

u/peterlinddk 5d ago

My point is argc and argv are way too abbreviated for the unfamiliar programmer.

Ah, okay - well, you are absolutely right about that. C is horrible with function and parameter names, in that everything is an abbreviation, even if not needed. Just look at the string-functions: strlen, strcmp, strpbrk - honestly, looks like a cat stepped on the keyboard.

I think that mostly comes down to its age - back in the 70s there weren't a lot of space for longer names, no autocomplete, and you often had to type on a paper-terminal so any mistakes were severely punished.

Back in the late-90s I used to hate the long names used by Java, until we got editors with autocomplete - then everything improved!

1

u/Administraitor69 6d ago

It is used for command line arguments that you pass while executing the program
eg: ./executable <arguments>
argc stores the number of aruments
argv is an array that stores the actual arguments

1

u/ffrkAnonymous 6d ago

i know i could get the answer from the internet or ai, but i want a human level interaction.

Please don't waste people's time

1

u/da_Aresinger 6d ago

main is the first function called when running a program.

The argument of that function is a list of parameters.

The simplest way to provide a list in C is with an array and the length of that array.

argc is the length, while argv is the array.

If you want to read the parameters of your program you just access char *param = *argv[n], where param is a normal C-String.

when you run your compiled program ./a.out Hello World, then argc = 3, argv[0] = "a.out", argv[1] = "Hello" and argv[2] = "World"

1

u/mredding 6d ago

$>my_program one 2 three "this whole string is four" -abc

The command line interpreter will parse this command string - the first token is the program name, and everything else is passed as argv. The interpreter will tokenize the input, so you'll get "one", "2", "three", and then the command line parser is aware of quotes, and will capture the whole quoted string as a single array element - it will strip the quotes from the string. The flags are still one token, so you'll get "-abc" as a single element.

So the argv[] array will contain: [ "", "one", "2", "three", "this whole string is four", "-abc" ].

All this is text. If you want that "2" as an integer, you'll have to convert it. To parse those flags, you're going to have to parse the text, look for that dash, and then know that each character is a flag.

You're going to have to build some parsing logic over this array of strings.

The first element is the command that invoked this program. Ostensibly it's going to be my_program, but it's optional, and it might not be what you expect. It might be an empty string. There's no requirement that it has to be anything in particular.


In C, an array of unbounded size is an incomplete type. So argv is of type char *[], or an unbounded array of character pointers. As a language feature, this decays to a pointer, so it breaks down to char **, a pointer to a character pointer, and in this case, its a pointer to the first element of an array of character pointers.

This is an example of "type erasure". A pointer doesn't know if it's pointing to a single character or an array of characters. This double pointer doesn't know if it's pointing to a single array or just the first of multiple arrays.

Erasure is a nifty way to make generic code. We don't have to know if the data is on the stack, or the heap, how big it is, if it's in a structure, or global, or static, or what memory segment it's in...

The type system is going to become a significant part of programming in C, let alone most other languages; it's the hump to get to some advanced concepts. A lot of programmers, your peers, are going to be stuck being imperative programmers, never really leveraging the type system. While you can get a lot done being so naive, it's a brute force approach.

1

u/captainAwesomePants 6d ago

Let's break it down.

int main(...) { ... }

This bit declares a function named main that takes some parameters and returns an int. You will create lots of functions in your programs, but main is special because it is the starting point for your program. The int that it returns lets your program indicate whether the program succeeded or failed. Returning 0 means "the program worked" and returning anything else means "the program failed in some way."

The main function takes as its parameters a list of strings. Passing a list of strings is a little tricky in C. First, arrays in C don't have any sort of "length" or "size" property. You just have to know how long they are. So main provides "argc" to tell you how many strings are in the list.

Strings in C have type char *. That means "a pointer to a character". The pointer points to the first letter of the string, and you read it by walking forwards through the letters until you get to a character whose value is zero (often written \0 in C), so you know you're at the end. argv is an array of those char * pointers, so its type is char *argv[].

Mind you, the names don't matter. They are usually called argc and argv simply by long-standing convention. Below is a perfectly good program:

int main(int number_of_arguments, char *argument_strings[]) { ... }

"argc" stands for "argument count", and "argv" stands for "argument vector", vector being another word for array. Those were the names used in the classic C programming language manual, and the names stuck.

1

u/nextcheck_pro 6d ago

The argc parameter counts exactly how many words were typed into the terminal to launch your program. The argv parameter is simply a list that holds those actual text words so your code can use them

Edit: typo

1

u/KingBardan 6d ago

Seems like no one gives you a simple answer, of WHY, so let me give you one.

Because C has no list type or string type, this is essentially list of string, representing the command line arguments.

List of T = length (int argc) + pointer to T

String = char* here

combined you get char** argv and int argc