简体   繁体   中英

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.

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. 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.

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.

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 . 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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