1. Technology

C Tutorial - About Pointers


9 of 10

Some More Examples of Pointers in C
Example 4 clears an array. Take a look at the loop terminating condition. The array has 50 elements so the element data[numitems] does NOT exist. The compiler uses the address of the first element beyond the array and is ok with it. Not a great technique but it shows some of the things you can get away with in C.
// ex4.c
#include <stdio.h>
#define numitems 50
int main(int argc, char* argv[])
   int data[numitems];
   int *ptr;

   for(ptr = data; ptr < &data[numitems]; ptr++)
      *ptr = 0;
    return 0;
Download Example 4

Example 5. You might recognise a version of this from this C Programming Problem blog entry as an example of code with errors in it. This is the correct version.

// ex5.c
#include <stdlib.h>

#define maxitems 1000
typedef int vector[maxitems];

int * addvectors(int * v1,int * v2) {
    int index;
    int * result = (int *) malloc(sizeof(vector)) ;
    int * temp=result;
    for (index =0;index < maxitems;index++)
        (*temp++)= *v1++ + *v2++;
    return result;

int main(int argc, char* argv[])
    vector a,b;
    int *c;
    int index;
    for( index=0; index < maxitems; index++){
       b[index]= index*1000;
    c= addvectors((int *)a,(int *)b) ;
    free(c) ;
    return 0;

Download Example 5.

On the Next Page : A complicated example. Slightly trimmed to fit!

©2014 About.com. All rights reserved.