Home > Software engineering >  using pointers inside functions
using pointers inside functions

Time:07-05

Why is it that everytime you declare pointer parameter inside the function and start to use it inside the function, you need to use asterisk next to the pointer variable everytime you use it somehow in the function. Why is it that way?

CodePudding user response:

If you come from a language like Java, where you do:

AbstractBeanFactorySingletonStubWrapper w = new MyBeanFactorySingletonStubWrapper();

You basically see that the only things you can do with the w reference, besides dereference it (e.g. call methods), is to test it against null.

That is trivial enough that you don't need any extra syntax to work with references.

In C and C , however, you can have the following:

int val[] = {5, 6};
int *p = val;
(*p)  ;
p  ;

There is a critical difference between (*p) and p : the former operates on the value, like in Java, whereas the latter operates on the pointer.

In summary, because C and C allow you to do many more things with pointers than languages like Java and C#, pointers require some kind of extra syntax.

You could ask "why not make dereference the "easy" syntax (like in Java) and require the extra syntax for these other pointer operations?". I don't know for sure, but but the very act of dereferencing a pointer, without any further operation on it, is its own an operation (which could segfault), so it seems appropriate to give it the extra syntax.

CodePudding user response:

Because that's how pointers work in C - to access the pointed-to object, you dereference the pointer using the unary * operator.

It's not automatic because sometimes you want to work with the pointer value itself.

  • Related