Solution for Exercise 08_08-daysweek.c
08_08-daysweek.c
#include <stdio.h>
void printall(char **w)
{
char *temp; /* pointer address storage */
/* swap elements 1 and 5 */
temp = *(w+1);
*(w+1) = *(w+5);
*(w+5) = temp;
while(*w)
puts(*w++);
}
int main()
{
char *weekdays[] = {
"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday",
"Sunday", NULL
};
printall(weekdays);
return 0;
}
Output
Monday
Saturday
Wednesday
Thursday
Friday
Tuesday
Sunday
Notes
* In the output you see that the strings Saturday and Tuesday are swapped.
* The printall() function echoes what's presented in the book. The argument is **w, which represents an array of pointers (strings).
* Character pointer temp is used for the swap. It's a character pointer in that it holds a string's address.
* The first and fifth pointers are swapped. These are at offset 1 and 5; 1 is the second element and 5 is the sixth.
* The expression *(w+1) represents the second element (Tuesday). It's string's address, which is saved in the temp pointer variable.
* The expression *(w+5) represents the fifth element (Saturday).
* Beyond the weird pointer notation, the swap takes place like any other variable swap in C. Remember that it's the addresses that are swapped; the string's contents are unaffected.
Copyright © 1997-2025 by QPBC.
All rights reserved
