strcpy的原理本身就是内容的复制,虽然参数均为地址.
直接,代码如下:
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> bool str_in(char **); void str_sort(char *[], int); void swap(void **p1,void **p2); void str_out(char *[], int); const size_t BUFFER_LEN = 256; const size_t NUM_P = 50; int main(void){ //初始化 char *pNum[NUM_P]; int count = 0; //输入 printf("请依次输入相关名称文段:\n"); for( ; count < NUM_P; count++){ if(!str_in(&pNum[count])){ break; } } //排序 str_sort(pNum,count); //输出 str_out(pNum,count); /*供观察*/ printf("%p %p %s\n",pNum,*pNum,*pNum); printf("%p %p %s\n",pNum,pNum[1],pNum[1]); printf("%p %p %s\n",pNum,*(pNum+1),*(pNum+1)); printf("%p %p %s\n",pNum,*(pNum+2),*(pNum+2)); return 0; } bool str_in(char **pString){ char buffer[BUFFER_LEN]; if(gets(buffer) == NULL){ exit(1); } if(buffer[0] == '\0'){ return false; } *pString = (char*)malloc(strlen(buffer) + 1); if(*pString == NULL){ exit(1); } strcpy(*pString , buffer); printf("%p %p %s\n",pString,*pString,*pString); return true; } void str_sort(char *p[], int n){ char *pTemp = NULL; bool sorted = false; while(!sorted){ sorted = true; for( int i = 0; i < n-1; i++) if(strcmp(p[i],p[i+1]) > 0){ sorted = false; swap(&p[i],&p[i+1]); } } } void swap(void** p1,void** p2){ void *pt = *p1; *p1 = *p2; *p2 = pt; } void str_out(char *p[], int n){ for( int i = 0; i < n; i++){ printf("%s\n",p[i]); /*仅便于观察*/ //free(p[i]); //p[i] = NULL; } } 执行结果如下: lnz@lnz:~/c_test$ ./a.out 请依次输入相关名称文段: 12345 0x7fff25caf920 0x23ce830 12345 125 0x7fff25caf928 0x23ce850 125 235 0x7fff25caf930 0x23ce870 235 17 0x7fff25caf938 0x23ce890 17 12345 125 17 235 0x7fff25caf920 0x23ce830 12345 0x7fff25caf920 0x23ce850 125 0x7fff25caf920 0x23ce850 125 0x7fff25caf920 0x23ce890 17 lnz@lnz:~/c_test$ 可见,静态分配在栈中,而动态分配在堆中;并且这里排序交换的参数是指针数组的值,即文段的地址.
