# C Pointers and Functions

Pointers and functions get on very well. Whenever data is to be passed to a function, especially large amounts of them, it is easier to pass a pointer to a function and to get back a pointer as the return value of the function.

Now, consider the very simple problem of interchanging two integer values. Suppose A is storing 5 and B is storing 10, after exchanging A should hold 10 and B should hold 5 obviously another temporary location, temp, is used to hold one of the values, while interchanging is taking place.

### More on pointers and functions

``````void exchange (pint1, pint2)
int *pint1, *pint2;
{
int temp;
temp = *pint1;
*pint1 = *pint2;
*pint2 = temp;
}
main()
{
int i1 = -5, i2 = 66, *p1 = &i1, *p2 = &i2;
printf(“il = %d, i2 = %d\n”,i1,i2);

exchange(p1,p2);
printf(“i1 = %d”, i2 = %d\n”, i1,i2);

exchange(&i1, &i2);
printf(“i1 = %d, i2 = %d\n”,i1,i2);
}
``````

OUTPUT:

``````i1 = -5, i2 = 66
i1 = 66, i2 = -5
i1=-5, i2 = 66
``````

Now consider a more complicated program. The function here searches for a particular value in a linked list. If it is found, it returns a pointer to the node holding the value. Otherwise, it returns a null pointer.

``````struct entry
{
int value;
struct entry *next;
};

struct entry *find_entry (1pointer, match_value)
struct entry *lpointer;
int match_value;
{
while (lpointer !=(struct entry *) 0)
if (lpointer->value = = match_value)
return (lpointer);
else
lpointer = lpointer->next;
return (struct entry *) 0);
}

main()
{
struct entry n1,n2,n3;
struct entry *lptr, *list_start = &n1;
int i,search;
n1.value = 100;
n1.next = &n2;
n2.value = 200;
n2.next = &n3;
n3.value = 300;
n3.next = (struct entry *) 0;
printf(“ Enter value to locate:”);
scanf(“%d”, &search);

if(lptr != (struct entry *) 0)
printf(“Found %d\n”,lptr->value);
else
}
``````

OUTPUT:

``````Enter Value to locate: 200
Found 200.
Enter Value to locate: 400 (Re-run) 