Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass a value while executing c program in terminal

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading