我有一个函数指针的简单测试代码:
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;
}
代码构建并成功运行。打印出“Hello world”字符串。
但是,我不明白的是,函数 PrintHello(char*)
接受一个指向字符串的指针 作为参数。但是我的代码是通过Function Pointerptr("world")
来调用这个函数的,其中我直接将字符串"world"传递给函数,而不是指针串起来。为什么有效?
最佳答案
在 C 中,字符串文字的类型是 char []
。将字符串文字传递给函数意味着您将指针传递给字符串的第一个 char *
类型的元素。函数调用
ptr("world");
相当于
char name[] = "world";
ptr(name); // Name decays to pointer to first character of the string literal.
应该注意的是,字符串文字是不可修改的,因此 ptr("world");
中的 "world"
但对于 char 则不是这样
数组。
在 C++ 中,字符串文字的类型为 const char []
。这意味着函数 ptr
必须有一个类型为 const char *
的参数,而不是 char *
。 (const char []
将衰减为 const char *
)。
关于c++ - 函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28604800/