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.

7
  • Search for argv and argc Commented Oct 3, 2022 at 10:12
  • Does this answer your question? Parsing command-line arguments in C Commented Oct 3, 2022 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. Commented Oct 3, 2022 at 10:14
  • Maybe read: stackoverflow.com/questions/41981565/… Commented Oct 3, 2022 at 10:14
  • 2
    Or a complete code example here: man7.org/linux/man-pages/man3/strtol.3.html Commented Oct 3, 2022 at 10:17

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

4 Comments

Am using: gcc -Wall -Werror test.c -o test, so it won't even compile. Thanks for the answer.
is says that variable ‘pname’ set but not used , and for strtol do i have to #include something ?
@Marwane The code compiles without error on my side. As for strtol comes alongstdlib.h
@Marwane, good look in your search!!! you are the best! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.