Swapping Strings – Solution

This month’s Exercise involves swapping elements between two string arrays. A number of solutions exist (as always), but because the “strings” are really pointers, the solution can be very specific. Yes, you just might have to use that dratted ** notation. Brace yourselves.

{yourselves}

Ha! C humor . . .

In the main() function, presented in the Exercise’s post, both functions show_arrays() and swap_arrays() are shown as the following statements:

show_arrays(beatles,stones);
swap_arrays(beatles,stones);

The pointer arrays are passed name-only. Because they’re pointer arrays, the function prototypes use the ** notation:

void show_arrays(char **b, char **s)

and

void swap_arrays(char **b, char **s)

If the functions swallowed strings, you’d use *b and *s as arguments. But an array of strings, or an array of pointers, requires the ** notation. Click here to read my Lesson on pointer-pointers, if you need a review.

The nifty thing, for those of you who detest pointers, is that once you’re inside the functions, you can again use array notation to show or swap the string elements. Here’s my solution for the show_arrays() function:

void show_arrays(char **b, char **s)
{
	int x;

	printf("Beatles =");
	for(x=0;x<4;x++)
		printf(" %s",b[x]);
	putchar('\n');
	printf("Stones =");
	for(x=0;x<4;x++)
		printf(" %s",s[x]);
	putchar('\n');
}

The printf() statements use b[x] and s[x] to display the strings. I could have written the expression in pointer notation, which would be *(b+x) and *(s+x), respectively, but array notation is easier to read.

Here is my solution for the swap_arrays() function:

void swap_arrays(char **b, char **s)
{
	int x;
	char *temp;

	for(x=0;x<4;x++)
	{
		temp = b[x];
		b[x] = s[x];
		s[x] = temp;
	}
}

Again, I use array notation within the function, which makes the solution look very similar to the solution for last month’s integer array-swapping function. The *temp variable is required to swap the pointers. It doesn’t need to be **temp because it’s referencing a string and not the string array.

Click here to view my solution.

When you swap pointers, you don’t affect the memory the pointers reference; the strings in the code continue to dwell in memory, safe and unmolested. The pointers, however, are swapped freely.

If you attempted a solution that involved swapping the string elements, well, wow! And if it works, congratulations, but it was a lot more overhead than is required so solve the Exercise.

Leave a Reply