I have a simple c program test.c
that increments a variable:
get(var); //get var when executing test.c
var = var 1;
printf(%d,var);
And i want to set var
when i execute the program:
./test 15
i want to store 15 in var
in my program and use it.
How can i do that ?
I really tried to search for this but didn't find anything.
CodePudding user response:
This is just an example to get you started your further searches
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
char *pname;
int v;
if (argc >= 1) {
pname = argv[0];
printf("pname = %s\n", pname);
}
if (argc >= 2) {
v = strtol(argv[1], NULL, 10);
printf("v = %d\n", v);
}
return 0;
}
Run as:
$ ./a.out
pname = ./a.out
$ ./a.out 1234
pname = ./a.out
v = 1234
As you may have guessed, the argc
and argv
describe the input data passed at execution time.
The argc
indicates how many arguments were passed to the program. Note that there is ALWAYS at least one argument: the name of the executable.
The argv
is an array of char*
pointing to the passed arguments. Thus, when calling ./a.out 1234
you get two pointers:
- argv[0]:
./a.out
. - argv[1]:
1234
.