Declaration and Assignment of Pointer

Now as we know meaning of & and * operators. We are going to declare and assign a pointer variable. Both are explained below. But the first most important thing about pointers is, “Data type of pointer and data type of variable (whose pointer we are creating) must be the same”. This means we want to make a pointer ‘p’ for variable ‘a’ then the data type of both ‘p’ and ‘a’ must be the same.

Pointer declaration

Syntax of declaring pointer is as written below.

<data type>   *<pointer name>;

Let us understand by example.

int a;
int *p;

As written above, there is a variable ‘a’ of data type int. If we want to make a pointer of the variable ‘a’ then its data type should be the same as ‘a’. So pointer ‘p’ is declared of int data type.

Pointer assignment

There are 2 methods/syntax for pointer assignment. But using both, the result is that, ‘p’ is storing the address of variable ‘a’. Means ‘p’ is a pointer to ‘a’. Both are listed below.

Syntax 1: When we want to do pointer assignment along with pointer declaration.

<data type>   *<pointer name> =  &(<name of variable whose pointer is this>);

Now let us understand this by the same above example. ‘a’ is the int variable and ‘p’ is a pointer of a.

int a;
int *p = &a;

Syntax 2: When we want to do pointer assignment after pointer declaration.

<pointer name> =  &(<name of variable whose pointer is this>);

Let us understand it by the same example. ‘a’ is the int variable and ‘p’ is the pointer of a.

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

Example of pointer declaration and assignment using pointer assignment syntax 1

In the below example ‘a’ is the int variable and ‘p’ is a pointer of ‘a’. This means ‘p’ stores the address of variable ‘a’. So the value of &a and p should be the same. That is proved by the output that &a and p, both are having the same value which is the address of variable ‘a’. And *p is *(&a) = a. Which is also shown at output.

#include<stdio.h>
#include<conio.h>
void main()
{
  int a=2;
  int *p = &a;
  clrscr();
  printf("address of a = %u \n",&a);
  printf("address of a = %u \n",p);
  printf("value of a = %d \n",a);
  printf("value of a = %d \n",*p);
  printf("value of a = %d \n",&(*a));
  getch();
}

Output:

Example of pointer declaration and assignment using pointer assignment syntax 2

#include<stdio.h>
#include<conio.h>
void main()
{
  int a=2;
  int *p ;
  p = &a;
  clrscr();
  printf("address of a = %u \n",&a);
  printf("address of a = %u \n",p);
  printf("value of a = %d \n",a);
  printf("value of a = %d \n",*p);
  printf("value of a = %d \n",&(*a));
  getch();
}

Output:

Learning from this blog:

  1. How to declare a pointer?
  2. How to assign value to a pointer?
  3. Methods for pointer assignment?
  4. How to use & and * in the pointer?
  5. How to write code for the pointer?
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments