I have a simple test code for Function Pointer:
void PrintHello(char *name)
{
printf("Hello %s\n", name);
}
int main(int argc, const char * argv[])
{
//ptr is a function pointer
void (*ptr)(char*);
ptr = PrintHello;
ptr("world");
return 0;
}
The code build & run successfully. The "Hello world" string is printed out.
But, what I don't understand is, the function PrintHello(char*) accepts a pointer to string as argument. But my code calls this function through Function Pointer ptr("world"), in which I directly passed the string "world" to the function, not a pointer to string. Why it works?
char, not a pointer to a stringchar*isn't a pointer to string."hello"is actually aconst char*. SO might not be the best place to learn the basics of c++ BTW.const char *, not achar *. You are getting away with it because you're compiler is being lenient (this usage used to be commonplace, so compilers may choose to support it even though it is not strictly legal).CandC++. This is a difference between the two: In C++"foo"has typeconst char[4], decaying toconst char *. InC, you don't get theconsts."hello"is an array, not a pointer. And since when were basic questions frowned upon? This is perfectly answerable.