ilovetolearn
ilovetolearn

Reputation: 2060

Ubuntu passing command line arugments to C program

I am learning C programming, I wrote the sample code to accept parameters from terminal and print out the arguments.

I invoke the program like this: ./myprogram 1

I expected 1 to be printed out for the argument length instead of 2. why it is so? There was no spacing after the argument "1"

#include <stdio.h>
#include <stdlib.h>

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

    printf("%d", argc);

    return EXIT_SUCCESS;
}

Upvotes: 1

Views: 1574

Answers (2)

cnicutar
cnicutar

Reputation: 182649

The first argument, argv[0] is the name with which the program was invoked. So there are two arguments and the second, argv[1] is "1".

EDIT

Editing to make clear: argc should always be checked. However uncommon, it is perfectly legal for argc to be 0.
For example on Unix, execvp("./try", (char **){NULL}); is legal.

Upvotes: 7

onemasse
onemasse

Reputation: 6584

"./myprogram" counts as the first argument.

Upvotes: 2

Related Questions