Chris Camacho
Chris Camacho

Reputation: 1174

function that can NULL a passed pointer

at the moment I have

void clistDeleteNode(clist_t *list,cnode_t **pnode) {
    cnode_t *node=*pnode;

    /* stuff done with node here, removed for clarity */

    free(*pnode);
    *pnode=0;
}

which is called with

clistDeleteNode(list,&aNode);

The function automatically NULL's the end user pointer after its freed - I do this as it makes debugging and leak checking easier.

is there a more elegant way to pass a pointer to a function such as it an be modified without having to use *&*aNode ? (from the end users point of view)

Upvotes: 0

Views: 156

Answers (4)

Filip Roséen
Filip Roséen

Reputation: 63797

No, there is no such thing as pass-by-reference in C, passing a pointer to the type which you'd like to update in another function is the only and recommended way to enable changing the original variable.


Not recommended.. really, please don't use it.

I've seen developer (long time since last though) use something as the below just to make things "easier", but to be honest I think it causes more headache than beauty.

#define REF(v) (&v)
#define REF_TO(type, v) type *v
#define DEREF(p) (*p)

void
func (REF_TO(int*, p))
{
  DEREF(p) = 0;
}

int
main (int argc, char* argv[])
{
  int *p;

  func (REF(p));

  return 0;
}

DO - NOT - USE - IT, SERIOUZLY.

Upvotes: 3

ecatmur
ecatmur

Reputation: 157334

Yes, but it's ugly; you can simulate reference parameters using array types and array-pointer decay.

typedef void (*void_ptr_ref)[1];
void func(void_ptr_ref p) {
    p[0] = 0;
}
int main() {
    void_ptr_ref p;
    func(p);
    /* do stuff with p */
}

Posix actually uses this (horrendous!) style for the jmp_buf type (used in setjmp.h).

This is only really worthwhile if your "pointer" type is intended to be used as an opaque type; you certainly don't want users having to double-indirect the void_ptr_ref p or have to cast it etc.

Upvotes: 0

AusCBloke
AusCBloke

Reputation: 18492

Unlike C++, there isn't a way of passing the address of aNode without having used the & operator in the calling function.

Using the pre-processor to hide what you're actually doing would most likely be considered a less "elegant" way than the above clear way.

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

No.

If you want a function to modify x, you need to pass &x to the function, no matter what the type.

You could hide this behind macros, but that may ultimately prove more confusing.

Upvotes: 2

Related Questions