关于用指针从小到大排序字符串的问题
- C/C++ code
#include <stdio.h>char hh(char *a,char *b);int main(int argc, char *argv[]){ char px(char *a,char *b, char*c); char p[3][50],*a,*b,*c,*temp="NULL"; a=p[0];b=p[1];c=p[2]; printf("请输入3个字符串\n"); scanf("%s %s %s",a,b,c); printf("你输入的字符串为:%s %s %s\n",a,b,c); px(a,b,c); printf("排序后的字符串为:%s %s %s\n",a,b,c); return 0;}char px(char *a,char *b,char *c){ char *temp; if(*a>*b) { temp=a; a=b; b=temp; } if(*b>*c) { temp=b; b=c; c=temp; } if(*a>*b) { temp=a; a=b; b=temp; }}
函数里面的检测大小条件能通过,为什么他们不会排序???
我在网上搜索了下,看别人写的没有利用函数的功能又可以更改指针指向的内容,他的代码如下
- C/C++ code
#include <stdio.h>#include <string.h>int main(){char c[3][81], *p1,*p2,*p3,*t; p1=c[0]; p2=c[1]; p3=c[2];printf("请输入三个字符串:\n");gets(p1); gets(p2); gets(p3);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("由小到大的顺序是:\n"); puts(p1);puts(p2);puts(p3);}
刚入门学C,表达方式估计也有一些不行~~。。。就想知道为什么在函数里不能该变指针的指向呢??
[解决办法]
因为c里面参数的传递是按值传递,即穿进函数处理的时候相当于对变量本身的一个拷贝进行操作
而不会印象到原变量的值,如下:
char *a,*b,*c;
//px
char *a1=a,*b1=b,*c1=c;
a1=b;//这样的改变a1,但是对a却没有任何影响。
[解决办法]
- C/C++ code
char px(char *a,char *b,char *c){ char *temp; if(*a>*b) { temp=a; a=b; b=temp; } if(*b>*c) { temp=b; b=c; c=temp; } if(*a>*b) { temp=a; a=b; b=temp; }}
[解决办法]
汗水啊,
char *temp;
if(*a>*b)
{
temp=a;
a=b;
b=temp;
}
if(*b>*c)
{
temp=b;
b=c;
c=temp;
}
if(*a>*b)
{
temp=a;
a=b;
b=temp;
}
char * a;
*a;是一个char你这样根本不能够完成,反而搞得稀巴烂…
没有限制使用什么函数吧?
先int Len = strlen( string/*要求长度的字符串*/ ;
char * Rlt;//存储结果
for( int i = 0 ; i < Len ; ++i )
{
内部进行比较排序……
}
以上是大体思路
[解决办法]
- C/C++ code
void px(char *a,char *b,char *c){ char *temp; if(*a>*b) { temp=a; a=b; b=temp; } if(*b>*c) { temp=b; b=c; c=temp; } if(*a>*b) { temp=a; a=b; b=temp; }}
[解决办法]
对的,这样能。
[解决办法]
字符串交换那里不是这么做的,你那样修改的是指针而不是指向的内容,这样函数返回后不能修改,要用strcpy或者参数是char**,用strcpy如下
char szTemp[256];
if(*a>*b)
{
strcpy(szTemp,a);
strcpy(a,b);
strcpy(b,szTemp);
}
下边类似