Copyright © tutorialspoint.com

# C - Array and Pointers Examples

## Printing pointers:

A program that prints out pointers and the values they point to:

    #include <stdio.h>

    int main()
    {
      int a = 10, b = 2;
      int *p1, *p2;
      p1 = &a;
      p2 = &b;
      printf("%p %p \n", p1, p2);
      printf("%d %d \n", *p1, *p2);
      return 0;
    }

This will produce following result:

    0xbfffdac4 0xbfffdac0
    10 2

## Passing pointers as parameters:

A program that swaps integers using a function that accepts pointers to the integers to be swapped:

    #include <stdio.h>

    void swap(int * q,int * p)
    {
      int temp = *p;
      *p = *q;
      *q = temp;
    }

    int main()
    {
      int a = 10, b = 2, x = 3, y = 5;
      printf("a,b,x,y: %d,%d,%d,%d\n", a, b, x, y);
      swap(&x, &y);
      swap(&a, &b);
      printf("a,b,x,y: %d,%d,%d,%d\n", a, b, x, y);
    }

It will produces following result:

    a,b,x,y: 10,2,3,5
    a,b,x,y: 2,10,5,3

## Passing pointers as parameters:

A program that computes the area and perimeter of a rectangle:

    #include <stdio.h>

    void rectangle(int a, int b, int * area, int * perim);

    int main()
    {
      int x, y;
      int area, perim;
      printf("Enter two values separated by space: " );
      scanf("%d %d", &x, &y);
      rectangle(x, y, &area, &perim);
      printf("Area is %d Perimeter is %d\n", area, perim);
      return 0;
    }

    void rectangle(int a,int b,int * area,int * perim)
    {
      *area = a * b;
      *perim = 2 * (a + b);
    }

This will produce following result:

    Enter two values separated by space: 10 15
    Area is 150 Perimeter is 50

## Passing arrays as parameters:

A program that reads elements and assign them in an array. Then, it prints the array elements out.

    #include <stdio.h>

    void get_array(int a[], int size);
    void prt_array(int a[], int size);

    #define SIZE 10

    int main()
    {
      int a[SIZE];
      get_array(a, SIZE);
      prt_array(a, SIZE);
      printf("\n");
      return 0;
    }

    void get_array(int a[], int size)
    {
      int i;
      printf("Enter 10 values, after each value press enter:\n " );
      for (i = 0; i < size; i++)
        scanf("%d", &a[i]);
    }

    void prt_array(int a[], int size)
    {
      int i;
      printf("Printing all values :\n");
      for (i = 0; i < size; i++)
        printf("%d\n", a[i]);
    }

This will produce something like:

    Enter 10 values, after each value press enter:
    10
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Printing all values :
    10
    2
    3
    4
    5
    6
    7
    8
    9
    10

Copyright © tutorialspoint.com