Question

My question is a simple one (I hope) about c syntax regarding pointer declaration. I am fully aware of how to declare a pointer, how its used and what the effects are, like as follows.

int *val_ptr;
int val =99;

val_ptr = &val;

However, what confuses me is why when we declare a pointer in C do we use the * Indirection (value of) operator? and not the & address of operator. If we are declaring a pointer would it not make sense to do so with &, because we are declaring an address right? Example:

int & val_ptr;
int val =99;

val_ptr = &val;

I know it's incorrect but to my mind that would seem more intuitive. What is it I'm missing in my conception of the * operator. I have not yet found a text book that gives me an explanation of why, they just show how. I know how, I would like to know why.

Thanks for reading.

Was it helpful?

Solution 4

You can't use & operator to declare pointer in C. Standard doesn't allow this. When you declare pointer in C like:

int *val_ptr;  

then * in the declaration is not the dereference (indirection) operator. But when this * comes in a statement then it performs indirection.

OTHER TIPS

The pointer declaration syntax tries to mimic pointer usage. When you have

int *ptr;

then *ptr is of the type int.

Declaration mimics use. If you have a pointer to an integer and you want to access the pointed-to value, you dereference the pointer with the * operator, like so:

x = *p;

The type of the expression *p is int; therefore, it follows that the declaration of p should be

int *p;

When you write:

int *mypointer;

you can think, "I declare that (*mypointer) is an int" (i.e, "my pointer will reference an int"), like this:

int (*mypointer);

Look that now,

int (&mypointer);

has no sense. What are you saying? the "address of my pointer value is an int" (that's true, but it's not your point).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top