views:

243

answers:

4

I have a typedef int my_type and i have a function which looks like

void my_func (my_type* x);

How should I use this func to modify x using the best practice?

+10  A: 

You can use the dereferencing operator '*' in your function :

void my_func (my_type* x)
{
  assert(x); // To protect from NULL pointer as mentioned in com.

  *x = 5; //for example
}
claferri
You'll want to protect against null pointers, at least: if (!x) return; or something.
assert(x) would probably be more sensible - never fail quietly!
anon
indeed. assert(x). failing quietly is sin #1 :p
Johannes Schaub - litb
be sure not to rely on `assert()` in production code - implement proper error handling via return values instead; also, a NULL-pointer dereference will segfault on most systems - you'll just not get the nice debug information of `assert()` without attaching a debugger
Christoph
+1  A: 

If you want to modify by assignment use claferri's answer. If you want to modify a member (if my_type is a struct) do:

void my_func(my_type* x) {
  x->member = 5;
}
Nick Fortescue
+2  A: 

If you use typedef you basically create a new type. As with all other types, just use the type like any other one. Just make sure to be consistent with typed -- if you use my_type for a variable use it everywhere for that variable. If you pass that type to a function use that type in the function, even if you know that the type is simply an int. And so on ...

bluebrother
In C, a typedef is an alias for a type, it is not a full new type.
Jonathan Leffler
+1  A: 

Use the * operator to dereference x!