Adarsh
Adarsh

Reputation: 893

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.

Upvotes: 0

Views: 111

Answers (3)

Giacomo Petrillo
Giacomo Petrillo

Reputation: 367

When you call:

function(p);

the code of function can read in the location pointed to by p the contents of a char array (i.e. 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), i.e. a pointer to a pointer to char while in the function declaration there is char * i.e. 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).

Upvotes: 1

Igor Pejic
Igor Pejic

Reputation: 3698

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.

Upvotes: -1

Ferenc Deak
Ferenc Deak

Reputation: 35458

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.

Upvotes: 1

Related Questions