C语言 用指针方法 输入3个字符串 按由小到大顺序输出

我的程序编译连接都没问题,运行的时候 ,输入一个字符串,然后回车就报错,是哪里错了呢。。。。各位大神给看看。。。

#include "stdafx.h"
#include "stdio.h"
#include "string.h"

void order(char *p1,char *p2,char *p3)
{
char *t;
if(strcmp(p1,p2)>0)
{t=p1;p1=p2;p2=t;}

if(strcmp(p3,p1)>0)
{t=p1;p1=p3;p3=t;}

if(strcmp(p3,p2)>0)
{t=p2;p2=p3;p3=t;}
}

int main(int argc, char* argv[])
{

char *p1=NULL,*p2=NULL,*p3=NULL;
scanf("%s\n",p1);
fflush(stdin);

scanf("%s\n",p2);
fflush(stdin);

scanf("%s\n",p3);
fflush(stdin);

order(p1,p2,p3);

printf("%s\n%s\n%s\n",p1,p2,p3);

return 0;
}

#include<stdio.h>

#include<string.h>

int main()

{

char str1[10],str2[20],str0[10];

printf("please input 3 strings");

gets(str1);

gets(str2);

gets(str0);

if(strcmp(str1,str2)>0)swap(str1,str2);/*字符串比较函数*/

if(strcmp(str2,str0)>0)swap(str2,str0);

if(strcmp(str1,str0)>0)swap(str1,str0);

printf("Now the otrder is:")

printf("%s\n%s\n%s"\nstr1,str2,str0);

return 0;

}

void swap(char*p1,*p2)

{

char str[10];

strcpy(str,p1);

strcpy(p1,p2);

strcpy(p2,str);

}

扩展资料:

strcpy用法:

1、strcpy(a+1,b+2)相当于将a[1]及它后面的内容复制为b[2]及它后面的内容。b[2]及后面为“2”,因此复制后a为“a2”;

2、strcat(a,c+1)相当于在a的末尾加上c[1]及其后面的部分,也就是“yz”。故运行后a为“a2yz”

strcpy把从src地址开始且含有'\0'结束符的字符串复制到以dest开始的地址空间,返回值的类型为char*。

strcat把src所指向的字符串(包括“\0”)复制到dest所指向的字符串后面(删除*dest原来末尾的“\0”)。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-10-17

你要先给指针分配空间,才可以往里面存东西。头文件带上stdlib.h,具体写法是

p1 = (char*)malloc(sizeof(char)*n)

其中n就是你要分配的大小,可以是一个固定的数,比如100,也可以是一个变量

第2个回答  2012-03-15
指针没有分配空间可以使用吗?
定义指针是不分配空间的,在使用前你得初始化,让它指向确定的地址才可以后续使用。
函数中是没法更改传入变量指针地址的!但可以更改其中的内容.
你的比较好像有问题,得不到所需要的:“从小到大”
#include "stdio.h"
#include "string.h"
int main(int argc, char* argv[])
{
char *t;
char *p1=NULL,*p2=NULL,*p3=NULL;
char ch1[20]={0},ch2[20]={0},ch3[20]={0};

p1=ch1;
p2=ch2;
p3=ch3;

printf("No1:");
scanf("%s",p1);
fflush(stdin);
printf("No2:");
scanf("%s",p2);
fflush(stdin);
printf("No3:");
scanf("%s",p3);
fflush(stdin);

if(strcmp(p1,p2)>0)
{t=p1;p1=p2;p2=t;}

if(strcmp(p1,p3)>0)
{t=p1;p1=p3;p3=t;}

if(strcmp(p2,p3)>0)
{t=p2;p2=p3;p3=t;}

printf("%s\n%s\n%s\n",p1,p2,p3);

return 0;
}
第3个回答  推荐于2017-10-17
//#include "stdafx.h"
#include "stdio.h"
#include "string.h"
//#include<iostream>
//using namespace std;

void order(char *p1,char *p2,char *p3)
{
char t;
if(strcmp(p1,p2)>0)
{t=*p1;*p1=*p2;*p2=t;}

if(strcmp(p1,p3)>0)
{t=*p1;*p1=*p3;*p3=t;}

if(strcmp(p2,p3)>0)
{t=*p2;*p2=*p3;*p3=t;}
}

int main()
{

char *p1=NULL,*p2=NULL,*p3=NULL;
char str1[10],str2[10],str3[10];

p1=str1;
scanf("%s",p1);
fflush(stdin);

p2=str2;
scanf("%s",p2);
fflush(stdin);
p3=str3;
scanf("%s",p3);
fflush(stdin);

order(p1,p2,p3);

printf("%s\n%s\n%s\n",p1,p2,p3);

return 0;
}

上面是正确答案,不可以直接给字符指针赋值,字符数组在编译时分配内存,有确定的首地址;字符指针变量,如果指向某个字符型数据,则给该变量分配内存,内存中分配地址值,如果还未赋值,则并未向指定的字符数据
正确格式应该是:
char*a;
char str[]
a=str;
scanf("%s",a);
而且,你的比较部分也不对,应该定义char t本回答被提问者采纳
第4个回答  2012-03-15
if(strcmp(p1,p2)>0)
{t=p1;p1=p2;p2=t;}
不能复制,运算,要调用strcpy
相似回答