Hi,
"main(int argc, char* argv[])"
When you invoke the main function from command line , it gets the total number of arguments passed in the variable argc . This approach doesnt work with user-defined functions.Is it possible in some other way to pass variable number of arguments to a function ? How ?
TIA
Nishant
Passing variable number of arguments to functions..
Moderator: Board moderators
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
There's no other way than va_arg to pass variable number of arguments to a function (unless you don't mind using assembler). Note that the original question was well defined ("is there some other way...").
As for functions that _pretend_ to have variable number of arguments (like main), try this
As for functions that _pretend_ to have variable number of arguments (like main), try this
Code: Select all
#include <stdlib.h>
#include <stdio.h>
int foo(int argc, char ** argv){
int acc = 0;
int i;
// main counts from 1, but we count from 0
for(i = 0; i < argc; ++i)
acc += atoi(argv[i]);
return acc;
}
int main(){
char * tab[] = {"1", "2", "123"};
printf("%d\n", foo(3, tab));
}
AFAIK, main() has no _pretensions_ whatsoever!Krzysztof Duleba wrote: As for functions that _pretend_ to have variable number of arguments (like main),
The C Standard(C99) defines two prototypes for main, viz.
Code: Select all
int main(void)
int main(int argc, char *argv[])
rarely (or, should I say, never) have variable number of arguments.
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
I agree with Krzysztof Duleba because it's the operation system who counts the arguments and put them in memory and save the pointers in the argv[] array.
as an exmple :
the operating system ( Ms-dos here / or some free alternative) would do several tasks before calling the program , as of taking the parametres and counting them and puts this number in argv , then puting them in memory and points the argv[] to them , then do some other stuff as loading the program into memory and call the main() funtion with those parametre , so at all there are two and not more (here in this case) so the code that Krzysztof Duleba gived resume a little that , but there is more to that because it's assembly more that it's C and that change the prospective of functions and arguments .
as an exmple :
Code: Select all
c:\>test.exe parametre1 parametre2