-6

while understanding the parameters of main function i.e, int argc, char* argv[]

i wrote a piece of code to understand these parameters.

#include <stdio.h>
int main(int argc,char*argv[])
{
    printf("test\n");
    printf("%d %c",argc,*argv[argc-1]);
    return 0;
}

This prints

test

1 F

here I don't understand why there is F as output. I mean how this is executed to result in output as F ?

I read about these perameters and main function at here and here. But still I don't understand how these works.

please explain .

EDIT: as mentioned in comments if I change the code to

printf("%d %s",argc,argv[argc-1]);

Now i'm getting the whole path of the file F:\file path

so does it mean argv[0] is the location of the file in drive?

Cœur
  • 37,241
  • 25
  • 195
  • 267
mssirvi
  • 147
  • 3
  • 14

2 Answers2

1

It is not defined in the C standard, but on Unix argv[0] is the name of the executable. Then argv[1] the first argument, etc. I think that this is also true, most of the time, on Microsoft's Dos and their Windowing OSes.

ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52
0

In simple words: When you give your commandline the instruction to run your program, you can append some text, which can be accessed in your program.

#include <stdio.h>
int main(int argc,char*argv[])
{
    printf("This is the path or name of your programm: ");
    printf("%s\n", argv[0]);

    if(argc > 1) {
        printf("This is the first argument you gave your programm: ");
        printf("%s\n", argv[1]);
    }

    if(argc > 2) {
        printf("This is the second argument you gave your programm: ");
        printf("%s\n", argv[2]);
    }
    return 0;
}

Try to run this example with:

<path_to_the_programm> Hallo Welt

You will see argc is an integer, which tells you how many arguments you gave the program. I hope it helped you.

Harald
  • 526
  • 4
  • 26