C & C++ pointers and why use them

Ever needed a function to return more than one variable?  If so, here is an example of how to do it using pointers:

#include <stdio.h>

void changeThem(int *X, int *Y, int *Z) 
{ 
    // here we manipulate the variables directly in 
    // memory using their addresses that we passed 
    // the function.  
    (*X) = 4; (*Y) = 6; (*Z) = 8; 
}

int main(void) 
{ 
    // initialize your integer variables 
    int X = 1; int Y = 2; int Z = 3; 
    // lets print them to the screen 
    printf("X:%d Y:%d Z:%d\n",X,Y,Z); 
    // now change them. Note the & which means you pass the address  
    // rather than the actual value 
    changeThem(&X, &Y, &Z); 
    // Print the variables again to see if they changed 
    printf("X:%d Y:%d Z:%d\n",X,Y,Z); 
}

So as you can see a function can return 2, 3 or more variables. Just use pointers.

Leave a Reply

Your email address will not be published. Required fields are marked *

*