Reputation: 29
Basically I want to pass main's argc
and *argv[]
to global variables, but am getting:
error:
args
has an incomplete typechar *[]
;
code:
int argi;
char *args[];
int main(int argc, char *argv[]){
argi = argc;
args = argv;
// blah bah blah
}
int foo(){
printf("argv[0]: %s\n", args[0]);
// ayy what it is.
}
Note: for some reason, I don't want to do foo(int argc, char *argv[])
and then in main calling it as foo(argc, argv);
So precisely said, I need to assign main's argc
and argv
to my global variables.
Upvotes: 0
Views: 1801
Reputation: 41
There is 1 problem:
argv
array type is quite restrictive when it comes to managing program parameters. Hence, the best practice is always about using the pointer of the argv
arguments array without altering its data structure: the char **argv
.
This way, you can easily transfer or use the array in your source codes.
Here is a quick example (tested with gcc
, amd64
, on Debian OS) derived from your code snippets:
#include <stdio.h>
int argi;
char **args;
int foo(void) {
int i;
for (i=0; i<argi; i++) {
printf("argv[%d]: %s\n", i, args[i]);
}
printf("\n");
return 0;
}
int main(int argc, char **argv) {
argi = argc;
args = argv;
return foo();
}
If you compile and run, you should get the following:
u0:demo$ ./a.out
argv[0]: ./a.out
u0:demo$ ./a.out one
argv[0]: ./a.out
argv[1]: one
u0:demo$ ./a.out one two
argv[0]: ./a.out
argv[1]: one
argv[2]: two
u0:demo$ ./a.out one two three
argv[0]: ./a.out
argv[1]: one
argv[2]: two
argv[3]: three
u0:demo$
UPDATE
Fri Apr 19 16:46:05 +08 2019
:
char *variable
, not char *variable[]
.Upvotes: 0
Reputation: 48672
Arrays and pointers aren't perfectly equivalent, even though they often appear to be convertible. Use char **argv
instead of char *argv[]
(and the same for the global), and this will then work.
Upvotes: 2