Saturday 17 November 2012

Programming with C - Pointers as Function Arguments

Programming with C -
Pointers as Function Arguments
Pointers as Function Arguments Earlier, we learned that functions in C receive copies of their arguments. (This means that C uses call by value; it means that a function can modify its arguments without modifying the value in the caller.) Consider the following function to swap two integers void swap(int x, int y) {     int temp;     temp=x;     x=y;     y=temp;     return; } The problem with this function is that since C uses call by value technique of parameter passing, the caller can not get the changes done in the function. This can be achieved using pointers as illustrated in the following program. Program 1.4: Program to swap two integers using pointers #include<stdio.h> main() {     int a, b;     void swap(int *a, int *b);     printf(" Read the integers:");     scanf("%d%d", &a, &b);     swap(&a, &b);        /* call by reference or call by address*/     printf(" \nAfter swapping:a=%d    b=%d", a, b); } void swap(int *x, int *y) {     int temp;     temp=*x;     *x=*y;     *y=temp;     return; } Execute this program and observe the result. Because of the use of call by reference, the changes made in the function swap() are also available in the main().

No comments:

Post a Comment