Problem Solving using C Language

0 of 77 lessons complete (0%)

Pointers

Pointers

 Pointer is a special type of variable which stores address of a variable.

 datatype *var_name;

This is a pointer variable declaration.

 int *ptr;

Here is the data type ‘int’ and *ptr is a pointer variable of integer pointer variable.

#include <stdio.h> 
void main() 
{ 
    int x = 10;
    int *ptr;
    ptr = &x;
    printf(“Value is : %d”,*ptr);
}
  • Since there is * in declaration, ptr becomes a pointer varaible (a variable that stores address of another variable)
  • Since there is int before *, ptr is pointer to an integer type variable int *ptr;& operator before x is used to get address of x. The address of x is assigned to ptr.

void main()
{
   int *p;
   int var = 10;
   p= &var;
   printf("Value of variable var is: %d", var);
   printf("\nValue of variable var is: %d", *p);
   printf("\nAddress of variable var is: %d", &var);
   printf("\nAddress of variable var is: %d", p);
   printf("\nAddress of pointer p is: %d", &p);
}

Output:
Value of variable var is: 10
Value of variable var is: 10
Address of variable var is: 0x7fff5ed98c4c
Address of variable var is: 0x7fff5ed98c4c
Address of pointer p is: 0x7fff5ed98c50

Let’s see this example

#include <stdio.h>

int main() 
{
    int num1, num2;
    int *ptr1; 

    num1=5;
    num2=6;

    ptr1 = &num1;  
    num1+=num2;
    printf("The sum of %d", *ptr1);

    return 0;
}