6

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?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Hill Tezk
  • 151
  • 4

3 Answers3

9

Confusingly, the asterisk in *pointer = 10 and the asterisk in int *pointer = &a mean two different things.

  1. *pointer = 10 Dereference the variable pointer and assign the value 10 to the result of the dereference operation.
  2. 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.
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
4

This:

int *pointer = &a;

is actually a shorthand, which is equivalent to this:

int *pointer;
pointer = &a;
gsamaras
  • 71,951
  • 46
  • 188
  • 305
1

your question can be answered in two ways.

  1. when you declare a pointer of type, say int, you do this "int *pointer" so this means you are declaring a pointer of type integer, but when you do this "int *pointer = a", this means you are initializing the pointer variable(pointer) by making it point to the address of a.

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"

  1. 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;

aditya rawat
  • 154
  • 10