将字符串排序输出:
#include <stdio.h>
int main()
{
int i = 0, j = 0;
char *temp = NULL;
char *myArray[] = { "aaaaa","cccc","bbbbb","11111" }; //元素存储的是字符串的首地址
int num = sizeof(myArray) / sizeof(myArray[0]);
printf("交换前:\n");
for (i = 0; i < num; i++)
{
printf("%s \n", *(myArray + i));
}
for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
if (strcmp(myArray[i], myArray[j]) > 0)
{
temp = myArray[i]; //交换的是首地址
myArray[i] = myArray[j];
myArray[j] = temp;
}
}
}
printf("交换后:\n");
for (i = 0; i < num; i++)
{
printf("%s \n", *(myArray + i));
}
system("pause");
return 0;
}
将输出和排序两个功能封装成函数后:
#include <stdio.h>
void printMyArray(char **buf,int num)
{
int i;
for (i = 0; i < num; i++)
{
printf("%s \n", *(buf + i));
}
}
void sortMyArray(char **buf, int num)
{
int i = 0, j = 0;
char *temp = NULL;
for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
if (strcmp(buf[i], buf[j]) > 0)
{
temp = buf[i]; //交换的是首地址
buf[i] = buf[j];
buf[j] = temp;
}
}
}
}
int main()
{
char *myArray[] = { "aaaaa","cccc","bbbbb","11111" }; //元素存储的是字符串的首地址
int num = sizeof(myArray) / sizeof(myArray[0]);
printf("交换前:\n");
printMyArray(&myArray,num);
sortMyArray(&myArray,num);
printf("交换后:\n");
printMyArray(&myArray, num);
system("pause");
return 0;
}
这里 char ** buf有点绕,分析一下:
myArray是一个指针,存储的是字符串的首地址,那么理所当然,就应该用char **buf来存储 myArray的地址了。
而myArray指的是第一个字符串的首地址,所以*buf也就是第一个字符串的首地址了。
扩展:buf[i] == *(buf+i)