开发者

Passing arguments to a C program

开发者 https://www.devze.com 2022-12-27 18:20 出处:网络
I was writing a C program where I use 6 variables a,b,c,d,e,f a,b,c are constant values which I should pass as an arguments from the command line.

I was writing a C program where I use 6 variables a,b,c,d,e,f

a,b,c are constant values which I should pass as an arguments from the command line.

d,e,f are going to be size of arrays of a structure.

typedef struct
{
   blah blah
} ex;

ex ex0[d];

I am very confused about how to pass all these as argument. Right now I have hard coded these values,which apparently I should not 开发者_如何学Gobe doing.


This should get you started:

int main(int argc, char* argv[]) {
    // argc - number of command line arguments
    // argv - the comand line arguments as an array

    return 0;
}


All params you pass to the program are stored in second argument of main function

int main(int argc, char* argv[]) // or int main(argc, char** argv)

so you can easily access 4th parameter by argc[3]. But it is not int, it is string, so you need to parse it. There are standard libraries for both taking you actual parameters from argc and parsing them for type you need. But in casual progrmas there is no point using them, so your code may look like this:

typedef struct
 {
  blah blah
 } ex;
int main(int argc, char* argv[])
{
 ex ex0[(int)argv[3]]; // i am not sure if it works on pure C, so you can try int atoi(char *nptr) from stdlib.h
}


Use command line arguments

int main(int argc, char* argv[]) // or int main(int argc, char **argv)
{
   // argc is the argument count
   //argv : The array of character pointers is the listing of all the arguments.
   //argv[0] is the name of the program.   
   //argv[argc] is a null pointer
}
0

精彩评论

暂无评论...
验证码 换一张
取 消