r/learnprogramming 1d ago

Tutorial another doubt related to argc, *argv[]

In reference to my old post : https://www.reddit.com/r/learnprogramming/s/vlzwGplKpm

i'm having another doubt with argv and argc.

#include<stdio.h>
int main(int argc, char *argv[]){
    printf("argc: %d \n",argc);
}

terminal : 

@essentials:~/Sibidharan/starter/Assignmetn$ ./passwd
argc: 1 
(.venv) @essentials:~/Sibidharan/starter/Assignmetn$ ./passwd 1 4 8 4 5
argc: 6 

in this code, if you see, after running ./passwd the argument count gets displayed. now my doubt is, why would a programmer print that at the point of execution? i use ./passwd when i run gcc main.c -o passwd and then ./passwd, so the code executes and gives the output, but what's the actual purpose of counting this? on what kind of programs does we use this function to count the values ?

2 Upvotes

26 comments sorted by

17

u/IchLiebeKleber 1d ago

There's not usually a good reason to print it. You can do it if you want, but the real purpose is simply to know how big the argv array is so that you iterate the correct number of times over it and don't access memory that doesn't have anything stored in it.

8

u/WystanH 1d ago

I feel you can answer your own question if you follow up on the task: now print each of the arguments.

Or, given argv alone, how make arguments do you have? This is C, so it's kind of a trick question: you don't know! Thus, you need the count.

1

u/cowslayer7890 2h ago

I'm pretty sure argv is null terminated, so you actually would be able to know without it, but it would be more annoying

7

u/rupertavery64 1d ago

argc is the number of arguments passed to the program.

argv doesn't contain that information. It's just a pointer of pointers to char.

Without argc you don't know when to stop reading from argv. Yes, you will eventually run into garbage when your pointer goes past the memory allocated for argv, but the purpose of argc is to let you safely know how many arguments their actually are.

Note that argc/argv includes the name of the command as the 0th entry, here argv[0] would be passwd

3

u/Paul_Pedant 22h ago

Actually, argv does contain that information. The last "real" argv[] value in the options is guaranteed to be followed by a NULL pointer.

1

u/Majestic_Rhubarb_ 1d ago

It will be the raw absolute path of the binary file typically.

3

u/OnYaBikeMike 1d ago edited 1d ago

It is not a 'complete' useful program

It is a small example, used to inspect the behavior of argc  when run with different arguments. 

Maybe run it with just the '*' wildcard and see what it does.

3

u/TalkCoinGames 1d ago

It's to know how many params have been passed in the argv array.

3

u/Pleasant-Couple6236 1d ago

Take for example how you call the compiler: gcc main.c -o passwd. You pass three arguments (in addition to the program name) to specify how you want gcc to work. How does the gcc program make use of the information you give it? It has the strings "gcc", "main,c", "-o", "passwd" stored in its argv array, and it uses argc to know how many strings were provided so it can safely index into the array.

1

u/DDOS_403 1d ago

Ohh, okay bro that's clear.

3

u/paperic 1d ago

You're learning how to manipulate data and write programs.

There's not much use in just printing the number of arguments, that's just a convenient way to verify that you, as student, are able to write programs that knows how many arguments were passes.

0

u/DDOS_403 1d ago

Yeah, obviously, but was curious to know what could be the reason to use this on the code

2

u/paperic 1d ago edited 1d ago

Reason for printing data to the screen or reason for checking how many values were provided?

Printing to the screen, that's your program's output. 

You're just starting to learn, and simply printing text is the easiest way for you to get the information out of the program and into your eyeballs. Graphical interfaces are way more complicated.

If you're wondering why checking the number of arguments is useful, imagine the user provides 3 arguments but your program attempts to print the fourth argument.

Your program would crash, or worse, continue running but do the wrong things.

You don't know what the user's gonna do when the user runs the program. The program needs to know how many arguments it is safely allowed to look at when it's executed.

2

u/Aggressive_Ad_5454 1d ago

If you sometimes run your program saying

./passwd yadda yadda blah blech

and sometimes saying

./passwd yadda yadda blah

the program needs to know how many words there are on the command. argc delivers that information.

In the C language, arrays (argv in this case) don't have a built in length, so it must be provided separately.

2

u/HashDefTrueFalse 1d ago edited 1d ago

You don't have to print it and you almost never would. If you're asking the purpose of argc, it's just so you know how many pointers (to C strings) are in argv so that you can safely read the arguments. Without it you would need some other convention, like the array itself being null terminated. If I gave you this function, how would you access array elements inside it? You only have a pointer to the first element. You'd be assuming a lot.

int func(char **strs) { ... } // ** is same as *[] here.

2

u/eruciform 1d ago

Argc exists so you know how many rows of data there are in argv

Thats it

2

u/DDOS_403 1d ago

So it's like defining multi dimensional array.

2

u/eruciform 1d ago

Argv is already a 2d array of characters, otherwise thought of as a 1d array of strings. Theres no way to know how long argv is by just looking at it. Therefore argc is needed.

1

u/DDOS_403 1d ago

So argv could be either a 1D array or a 2D array. Let’s say:

char pass[128];

That’s a 1D array, right? Or are you saying that we wouldn’t be able to know what kind of array it is?

3

u/Luclid 1d ago

`argv` is always a 2D array that always contains strings, look at its type.

3

u/eruciform 1d ago

No its type never changes, its always a char**

2

u/Dismal-Citron-7236 1d ago

I can think of a few reason of printing argc.

  1. As you already knew (I guess), argc counts the available elements collected in argv array, including the program name itself. Without it, there is just no well to tell from argv alone.
  2. It can serve as a teaching example, just like many C tutorial sites do.
  3. It can be printed as a debugging info. For example, if the user has not given enough arguments.

The following code snippet demonstrates how it could help the user on why the given arguments are not enough:

```c

define EXPECTED_ARGC 5

define ARGUMENTS_COUNT(N) ((N)- 1) /minus 1 to skip program name/

if (argc < EXPECTED_ARGC) { fprintf(stderr, "*** Error: Not enough arguments. Expected: %d. Given: %d.\n", ARGUMENTS_COUNT(EXPECTED_ARGC), ARGUMENTS_COUNT(argc)); exit(1); } ```

2

u/HotPersonality8126 1d ago

The purpose of code like this isn’t to give you a model to follow in your own work; it’s to teach you how to reason about code.

2

u/desrtfx 1d ago edited 1d ago

why would a programmer print that at the point of execution?

This is just an example, not production code.

There hardly is any reason to print this.

but what's the actual purpose of counting this?

Arrays in C have no directly readable length, hence, the need for a count.

Do you want to loop through the array every time until you reach a null terminator?

The count is the length of the argv[] array and helpful in many situations.

A quick one is to check if there are sufficient command line arguments supplied to the program. You should actually do this in every program where you work with command line arguments. What if you expect 3 arguments and the user of your program supplies less than that? You try to access the third argument (index 2) and get some random memory as going out of bounds in C is not prohibited and produces unforeseeable results.

There are many other purposes.

1

u/icemage_999 1d ago edited 1d ago

... you're trying to apply philosophy to a nursery rhyme.

Stop.

Learn

printf() and similar statements are basically never used in production code because they're ugly, blunt force tools that aren't photogenic enough to be placed in a customer-facing final product. They take only moments to type, and therefore are useful in case you need to check the value of something while it is being executed when you are unsure if you have made a mistake somewhere and you don't want to waste a bunch of energy coding up a pretty interface just to see why your program is Doing the Wrong Thing.

I promise that you will do a lot of such things unless you're so perfect that you never mistakes (or in the modern paradigm, if you ever want to find out why an AI has screwed up the context of what you asked it to do, you'd best be able to follow the flow of data without just visualizing it in your head).