by BehindJava

How to use Pointers for Variable Parameters in C Language

Home » cse » How to use Pointers for Variable Parameters in C Language

Using Pointers for Variable Parameters

Most C programmers first need to use pointers for variable parameters. Suppose you have a simple procedure in Pascal that swaps two integer values:

program samp;  
var  
    a,b:integer; 
 
procedure swap(var i,j:integer);    
var t:integer;    
begin      
    t:=i;      
    i:=j;      
    j:=t;    
end; 
  
begin    
    a:=5;    
    b:=10;    
    writeln(a,b);    
    swap(a,b);    
    writeln(a,b);  
end.

Because this code uses variable parameters, it swaps the values a and b correctly.

C has no formal mechanism for passing variable parameters: It passes everything by value. Enter and execute the following code and see what happens:

#include <stdio.h>   
 
void swap(int i, int j)    
{    
    int t; 
    
    t=i;    
    i=j;    
    j=t;  
} 
 
void main()  
{    
    int a,b; 
    
    a=5;  
    b=10;    
    printf("%d %d\n",a,b);    
    swap(a,b);    
    printf("%d %d\n",a,b);  
}

No swapping takes place. The values of a and b are passed to swap, but no values are returned.

To make this function work correctly, you must use pointers, as shown below:

#include <stdio.h>   
 
void swap(int *i, int *j)    
{    
    int t; 
    t = *i;    
    *i = *j;    
    *j = t;  
} 
 
void main()  
{    
    int a,b; 
    a=5;    
    b=10;    
    printf("%d %d\n",a,b);    
    swap(&a,&b);    
    printf("%d %d\n",a,b);  
}

To get an idea of what this code does, print it out, draw the two integers a and b, and enter 5 and 10 in them. Now draw the two pointers i and j, along with the integer t. When swap is called, it is passed the addresses of a and b. Thus, i points to a (draw an arrow from i to a) and j points to b (draw another arrow from b to j). Because the pointers have been established, *i is another name for a, and *j is another name for b. Now run the code in swap. When the code uses *i and *j, it really means a and b. When the function completes, a and b have been swapped.

Suppose you accidentally forget the & when the swap function is called, and that the swap line accidentally looks like this: swap(a,b);. This causes a segmentation fault. When you leave out the &, the value of a is passed instead of its address. Therefore, i points to an invalid location in memory and the system crashes when *i is used.

This is also why scanf crashes if you forget &--- scanf is using pointers to put the value it reads back into the variable you have passed. Without &, scanf is passed a bad address and crashes.