有关字符串和指针的问题(C),大虾帮忙看看啊~~

来源:百度知道 编辑:UC知道 时间:2024/06/14 15:57:51
这是一个输入三个字符串,然后按由小到大输出的,用指针,我写下了下面的程序后,不知为何运行的结果是乱码,还有一个警告:“可能在'temp'定义以前使用了它在 swap 函数中”,不知道如何改,请大虾帮忙看看啊~~
/*string compare */
#include <stdio.h>
#include <string.h>
#define M "I like China"
#define N "Today is Monday"
#define K "wonderful!"
char swap(char *pointer_1,char *pointer_2);
main()
{ char a[]=M,b[]=N,c[]=K;
char *p1,*p2,*p3;
printf("The original string is:'%s','%s','%s'.\n",a,b,c);
p1=a;p2=b;p3=c;
if (strcmp(p1,p2)>0)
swap(p1,p2);
if (strcmp(p1,p3)>0)
swap(p1,p3);
if (strcmp(p2,p3)>0)
swap(p2,p3);
printf("The new strings is: %s,%s,%s\n",*p1,*p2,*p3);
getch();
}

char swap(char *pointer_1,char *pointer_2)
{ char *temp;
strcpy(temp,pointer_1);
strcpy(pointer_2,pointer_1);
strcpy(poin

1.指针temp的指向不确定,应使用char *temp=NULL;
2.swap函数没有返回值,应改为void swap(..);
3.输出一个指针指向的字符串时,不加'*'号.应改为
printf(\"The new strings is: %s,%s,%s\\n\",p1,p2,p3);
下面为我改正后的程序:
/*string compare */
#include <stdio.h>
#include <string.h>
#define M \"I like China\"
#define N \"Today is Monday\"
#define K \"wonderful!\"
void swap(char *pointer_1,char *pointer_2);
main()
{ char a[]=M,b[]=N,c[]=K;
char *p1,*p2,*p3;
printf(\"The original string is:\'%s\',\'%s\',\'%s\'.\\n\",a,b,c);
p1=a;p2=b;p3=c;
if (strcmp(p1,p2)>0)
swap(p1,p2);
if (strcmp(p1,p3)>0)
swap(p1,p3);
if (strcmp(p2,p3)>0)
swap(p2,p3);
printf(\"The new strings is: %s,%s,%s\\n\",p1,p2,p3);
getch();