I am currently learning pointers in C. I feel confused about the initialization of a pointer. I might be asking silly questions, but I just want to make sure I understand and learn things right.
So, to initialize a pointer:
int a = 3;
int *pointer = &a;
*pointer = 10;
OR
int a = 3;
int *pointer;
pointer = &a;
*pointer = 10;
So far, I knew that " * " declares a pointer type.
*pointer is the value of whatever value in the address that the pointer points to.
& is the memory address of something.
I can understand 'pointer = &a' in the second case.
But, why do we set *pointer = &a in the first case above since *pointer represents the value in that address?
Why do we make the value in that pointer equals to the address of the variable in the first case when initializing the pointer?
ou should use www because today you have a small web site, and tomorrow you want a big web site. Really big.
Why is a wh -word. We use why to talk about reasons and explanations. Why did he leave home when he was 16? Why didn’t you tell Gemma? Why is the Earth round? He asked me why I wanted to leave the job. I wonder why he told nobody he was getting married.
We use why to talk about reasons and explanations. Why did he leave home when he was 16? Why didn’t you tell Gemma? Why is the Earth round? He asked me why I wanted to leave the job. I wonder why he told nobody he was getting married. I’m going home now. Why? When we reply to a negative statement, we usually say why not ?: I don’t like it here.
We can use why ever or why on earth to add emphasis and to show shock or surprise. We usually stress ever and earth: Beth has decided to go on holiday by herself this year. Why ever would anyone want to go on holiday alone? Why on earth has Julie bought me this expensive present?
Confusingly, the asterisk in *pointer = 10
and the asterisk in int *pointer = &a
mean two different things.
*pointer = 10
Dereference the variable pointer
and assign the value 10
to the result of the dereference operation.int *pointer = &a
Declare the variable pointer
to be of type int *
, and initialise it with the value &a
. No dereference takes place here. The asterisk is here to remind you that when dereferencing pointer
you will get an int
. In other words, this declares pointer
such that *pointer
is int
.This:
int *pointer = &a;
is actually a shorthand, which is equivalent to this:
int *pointer;
pointer = &a;
your question can be answered in two ways.
note that:- "int *pointer = a" this does not means you are dereferencing the pointer variable, this means you are initializing the pointer variable by making it point to "&a"
int *pointer = &a;
and
int *pointer; pointer = &a;
means the same thing int *pointer = &a; this can be considered as the shortcut for writing this
int *pointer;
pointer = &a;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With