简体   繁体   English

将指针传递给C中的函数

[英]Passing a pointer to a function in C

Function declaration is 函数声明为

void function (char *);

If p is a char pointer then what is difference between these two function calls. 如果p是一个char指针,那么这两个函数调用之间有什么区别。

function (p)

and

function ((char **) &p)

Are they both same. 他们俩都一样吗?

I would be thankful to the stack overflow family for any information on this topic. 我要感谢堆栈溢出系列提供有关此主题的任何信息。

void function ((char **) &p) if my memory is not cheating me is not valid C syntax. 如果我的内存没有欺骗我,则void function ((char **) &p)不是有效的C语法。 The closest you can get to the validity is to remove the inner ( and ) and compile as C++ an then it would be a reference to a pointer of a char pointer. 与有效性最接近的是删除内部()并作为C ++进行编译,然后它将作为对char指针的指针的引用。

The first one is just a "plain" char pointer. 第一个只是“普通”字符指针。

When you call: 你打电话时:

function(p);

the code of function can read in the location pointed to by p the contents of a char array (ie a string), or a single char variable or whatever data it expects. function代码可以在p指向的位置读取char数组(即字符串)的内容,单个char变量或所需的任何数据。

When you call: 你打电话时:

function((char **) &p);

the compiler will complain with: 编译器将抱怨:

warning: incompatible pointer types passing 'char **' to parameter of
  type 'char *'

because &p is of type char ** (in fact, the explicit conversion (char **) is unnecessary), ie a pointer to a pointer to char while in the function declaration there is char * ie pointer to char . 因为&p属于char **类型(实际上,不需要显式转换(char **) ),即,指向char的指针的指针,而在函数声明中有char *即指向char指针。 On runtime, function will not read a string or a single character as it may expect, but will read the bytes of a pointer to char as if they were a string (potentially causing a crash). 在运行时, function不会按预期读取字符串或单个字符,但会像对待字符串一样读取指向char的指针的字节(可能导致崩溃)。

Your idea is good: the operators * and & cancel each other when assigning values, but not in declarations, just like * and / , but the header: 您的想法很不错:赋值时,运算符*&互相取消,但不能像*/一样在声明中出现,但是标头是:

void function ((char **) &p);

can't be compiled by a C compiler. 不能由C编译器编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM