Home > OS >  How to interpret assignment to pointer in C
How to interpret assignment to pointer in C

Time:02-14

In C, the statement int *var_name; by convention means that *var_name is of type int, which implies that var_name is an integer pointer.

But now consider this sequence of statements.

int a = 5;
int *var_name = &a;

But here how are we assigning address of a to *var_name which is of type int?

CodePudding user response:

You are not assigning the address to *var_name, but to var_name. And this variable is of type "pointer to int", as you found.

Oh, and it is an initialization, not an assignment.

CodePudding user response:

That's just the way the syntax in C works.

int *p = &a;

is completely equivalent to:

int *p;
p = &a;

It's not so difficult to understand why it would not make sense if it worked the way you thought. Consider this code:

int *p;
p = &a;
*p = 42;

Now imagine flipping the last two statements, like this:

int *p;
*p = 42; // To which address do we write 42? p is not initialized.
p = &a;

So although the meaning of int *p = &a;, which is int *p; p = &a; might be unintuitive, it's actually the only sane way to define it.

CodePudding user response:

In this declaration

int *var_name = &a;

there is declared the variable var_name of the pointer type int * and this variable (pointer) is initialized by the address of the variable a.

It seems you mixing the symbol * in declarations and in expressions.

In declarations it denotes a pointer. In expressions it denotes the dereference operator.

Consider the following demonstration program

#include <stdio.h>

int main( void )
{
    int a = 5;
    int *var_name = &a;

    printf( "The address stored in var_name is %p\n", ( void * )var_name );
    printf( "The address of the variable a  is %p\n", ( void * )&a );

    printf( "The value of the object pointed to by var_name is %d\n", *var_name );
    printf( "The value stored in the variable a is %d\n", a );
}

Its output might look like

The address stored in var_name is 00EFFAC0
The address of the variable a  is 00EFFAC0
The value of the object pointed to by var_name is 5
The value stored in the variable a is 5

That is in this line

    int *var_name = &a;

*var_name means a declarator of a pointer type.

In this call

printf( "The value of the object pointed to by var_name is %d\n", *var_name );

*var_name means an expression with teh dereference operator *.

  • Related