char first[10]="monkey"; char second[10]="fish"; char* keep; char* sell; /* keep the monkey sell the fish */ keep = first; /* or &first[0] */ sell = second; printf("Keep the %s\n", keep); printf("Sell the %s\n", sell);
/* Change mind. Keep the fish, sell the monkey. */ /* Swap keep and sell */ char* temp; /* should be up top */ temp = keep; keep = sell; sell = temp; /* No strings have been copied! */ printf("Keep the %s\n", keep); printf("Sell the %s\n", sell);
Sorting some books char books[5][40] = {"Problem Solving in C", "Algorithm Development", "Web Design", "Database Managment", "The C Programming Language"};
/*An array of pointers:*/ char* bookP[5]; /* Have the pointer point to the books */ int i; for (i = 0; i<5; i++) bookP[i]=books[i]; /*The address of the book*/
/*Bubble sort the array, without moving any books! */ /* some variables we will need */ int last; /* subscript of last element of unsorted array*/ int i; /* index of first number in pair being compared */ char* temp;
int n=5; /*number of books */ for (last = n-1; last>=1; last--) for (i=0; i<= last-1; i++) if (strcmp(bookP[i],bookP[i+1])>0) /*swap the pointers*/ { temp=bookP[i]; bookP[i]=bookP[i+1]; bookP[i+1]=temp; }
/* Print out the books in alphabetical order */ for (i=0; i<n; i++) printf("%s \n", bookP[i]); /* Print out the books in stored order */ for (i=0; i<n; i++) printf("%s \n", books[i]);