Function pointers in C
Why does the following print 1
. I was expecting it to print the address of the function pointer.
#include <stdio.h>
int main(main) {
printf("%i",main);
return开发者_开发知识库 0;
}
Pointers must be printed with %p
. Anyway here there's an "aliasing" problem, rather odd but that's it: main gets the value of the first argument to function main that is, what usually is called "argc". if you call it with more arguments, you should see bigger number.
Because the first argument of a program's main
function is the argument count (plus one, since the program's name is the first argument) at runtime. Assuming you invoked your program with no arguments, that value will be populated with an integer.
Many people traditionally use main
with the following signature:
int main(int argc, char **argv);
If you remove the parameter, you might get what you want:
int main() {
printf("%i", main);
return 0;
}
If that doesn't work, try declaring int main();
above the function definition.
If THAT doesn't work, ask yourself why you're doing this in the first place. :-P
you declared a param with the name "main
" - this param corresponds to the first param of the main
function in C
which in turn is usually called "argc
" which in turn is 1 if you start you program whithout any commandline params.
The first parameter to main is usually called argc
which tells you how many arguments the program was run with. Since you are running this with no arguments the value will be 1 (The name of the executable) If you run this from command line with extra arguments separated by spaces that number will increase.
This is equivalent to
#include <stdio.h>
int main(int main) {
printf("%i",main);
return 0;
}
So main
is the first parameter of the main
function. If called without parameters the size of the (normally following) argv array is 1, argv[0] holding the name of the process.
You include main
as a parameter to the function main
. This gets the first value normally given to main
, that is, the size of the arguments passed to the program. If you don't pass arguments to the program, still the arguments hold the name of the program being executed, so the size of the argument list is 1, what it is printed.
精彩评论