中南勘察设计院招聘网:有关字符串和指针的问题(C),大虾帮忙看看啊~~

来源:百度文库 编辑:神马品牌网 时间:2024/05/08 15:50:35
这是一个输入三个字符串,然后按由小到大输出的,用指针,我写下了下面的程序后,不知为何运行的结果是乱码,还有一个警告:“可能在'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(pointer_2,temp);
return;
}

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();
}

void swap(char *pointer_1,char *pointer_2)
{ char *temp=NULL;
strcpy(temp,pointer_1);
strcpy(pointer_2,pointer_1);
strcpy(pointer_2,temp);
}

函数swap需修改:
在你的swap函数中,你定义了指针temp,但是指针temp并没有申请空间;
你必须这样做;
void swap(char *pointer_1,char *pointer_2)
{
char *temp;
int pointer_1_len = strlen(pointer_1);
temp = (char *)malloc((pointer_1_len + 1) * sizeof(char));

strcpy(temp,pointer_1);
strcpy(pointer_2,temp);
strcpy(pointer_1,pointer_2);

free(temp);
}
在C语言中,指针只代表地址,不代表一定拥有空间,该函数问题是内存泄漏;

swap函数里面试试看该成
strcpy(temp,pointer_1);
strcpy(pointer_2,temp);
strcpy(pointer_1,pointer_2);