Using Pointers in C

This example is based on our page on pointers in Pascal so that you can compare the code. We combine the first two Pascal demonstrations into one C program.

#include <stdio.h>

int main()
{
  int int1, int2;
  int *ptr_int;      // ptr_int points to an integer
  int1 = 42;
  ptr_int = &int1;   // Assigns the address of int1 to ptr_int.
  int2 = *ptr_int;   // Dereferences ptr_int and assigns the result to int2.
  printf("int2: %d\n", int2);

  int int_array[2] = {10, 20};
  ptr_int = &int_array[0];
  ptr_int++;
  int2 = *ptr_int;
  printf("Second value in array: %d", int2);
}

Output:

int2: 42
Second value in array: 20

Pointers to Structs

This demonstration shows the syntax for handling a field of a record (struct) that is a pointer to another record. For a real application of record pointers, see our Pascal demonstration of linked lists.

#include <stdio.h>
#include <string.h>

struct score_rec
{
  char surname[15];
  int score;
  struct score_rec *next;
};

int main()
{
  struct score_rec r1, r2;
  r1.score = 10;
  strcpy(r1.surname, "Sugar");
  r1.next = &r2;
  r2.score = 20;
  strcpy(r2.surname, "Gates");
  r2.next = &r1;
  // Access the other record showing both forms of syntax
  // ( dereferenced pointer with . or pointer with -> )
  printf("%s %s", (*r1.next).surname, r2.next->surname);
  return 0;
}
    

Output:

Gates Sugar

Passing by Reference

C does not have Pascal's var parameter for enabling a routine to change the value of a variable passed to it so to achieve this you need to pass an address of a variable (or a declared pointer) as follows.

#include <stdio.h>

void increment(int *num)
{
  (*num)++;
}

int main()
{
  int my_int = 99;
  // Pass the address directly
  increment(&my_int);
  printf("my_int after increment: %d\n", my_int);

  // Pass the address via a declared pointer
  int *int_ptr;
  int_ptr = &my_int;
  increment(int_ptr);
  printf("my_int after second increment: %d\n", my_int);
  return 0;
}
    

Output:

my_int after increment: 100
my_int after second increment: 101

Many inbuilt C routines such as scanf accept one or more addresses/pointers.

You pass an array to a routine by reference as if you had passed an address or pointer. We give an example in the later section on arrays.

Programming - a skill for life!

How to apply your knowledge of Pascal when learning C/C++