0

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.

Marwane
  • 333
  • 3
  • 13
  • Search for argv and argc – Support Ukraine Oct 03 '22 at 10:12
  • Does this answer your question? [Parsing command-line arguments in C](https://stackoverflow.com/questions/9642732/parsing-command-line-arguments-in-c) – 9769953 Oct 03 '22 at 10:13
  • 1
    The suggested duplicate may be a bit overkill for your question, but I think it has all the information. For a simple argument like one number, there is probably no need for getopt or argp, but these may be convenient to keep in mind. – 9769953 Oct 03 '22 at 10:14
  • Maybe read: https://stackoverflow.com/questions/41981565/clarification-on-argc-and-argv – Support Ukraine Oct 03 '22 at 10:14
  • 2
    Or a complete code example here: https://man7.org/linux/man-pages/man3/strtol.3.html – Support Ukraine Oct 03 '22 at 10:17
  • _I really tried to search for this but didn't find anything._ This is homework assignment. You are not asked to search internet for a solution, you are asked to solve the problem yourself. Don't search and write valid code (the code you post is incorrect, just will not compile) You are requested to learn to program, not to learn to search internet for the already made code. – Luis Colorado Oct 04 '22 at 10:51
  • I’m voting to close this question because the PO is asking for an already made solution to his homework. – Luis Colorado Oct 04 '22 at 10:53

1 Answers1

3

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.
Jib
  • 1,334
  • 1
  • 2
  • 12