Skip over navigation

Why Use Pointers?

Problems

Passing Modifiable Arguments to Functions

Dynamic Memory Allocation

Problem : Write a function that takes pointers to two integers and swaps the values stored at those addresses.

void swap(int *a, int *b)

Problem : Why doesn't this function swap the values correctly?


void swap(int a, int b)
{
	int temp = a;
	a = b;
	b = temp;
}

Because all changes made inside the function are being made to the values stored in a and in b, which are copies of the variables passed in, not the actual variables themselves. So, although the function does the swap operation correctly, as soon as the function returns all those changes go away.

Problem : Write a function which takes an array of 5 integers and sets all the values to 0.


void set_to_zero(int arr[5])
{
	for(i=0; i<5; i++) arr[i]=0;
}

Problem : Write a function void set_to_NULL(char **ptr); which takes a pointer to a pointer to a character and sets the memory at that address to NULL.


void set_to_NULL(char **ptr)
{
	*ptr = NULL;
}

Problem : CHALLENGE: Write a swap function that doesn't use a temporary variable for storage. Hint: use the XOR operator. Are there any cases in which this won't work?

void swap(int *a, int *b) This won't work if a and b both point to the same memory.

Follow Us