辣鸡然然的日志——006字符串指针(比较字符串大小并排序引发的惨案)

#include <cstdio>
#include <cstring>
int main()
{
char a[10],b[10],c[10];
char *x, *y, *z;
int t;
gets(a);
gets(b);
gets(c);
x = &a[0];
y = b;
z = c;
if(strcmp(a,b)>0)
{
t = *x;
*x = *y;
*y = t;
}
if(strcmp(b,c)>0)
{
t = *y;
*y = *z;
*z = t;
}
if(strcmp(a,c)>0)
{
t = *x;
*x = *z;
*z = t;
}
puts(a);
puts(b);
puts(c);
return 0;
}

乍一看好像没什么问题但是运行就出问题了

指针*x,*y,*z指向的是字符串的首地址

也就是说指向的是a[0],b[0],c[0]

互换指针,互换了字符串的首地址

就只互换了字符串的首字母

这样的排序遇到同样首字母的字符串也没招(虽然本身就有问题)

所以要互换指针指向的内容,而不是指针的指针。。。

错误示范:

#include <cstdio>
#include <cstring>
int main()
{
char a[10],b[10],c[10];
char *x, *y, *z, *t;
gets(a);
gets(b);
gets(c);
x = &a[0];
y = b;
z = c;
if(strcmp(x,y)>0)
{
t = x;
x = y;
y = t;
}
if(strcmp(y,z)>0)
{
t = y;
y = z;
z = t;
}
if(strcmp(x,z)>0)
{
t = x;
x = z;
z = t;
}
puts(a);
puts(b);
puts(c);
return 0;
}

正确示范:

(考虑xyz关系)

#include <cstdio>
#include <cstring>
int main()
{
char a[10],b[10],c[10];
char *x, *y, *z, *t;
gets(a);
gets(b);
gets(c);
x = &a[0];
y = b;
z = c;
if(strcmp(x,y)>0)
{
t = x;
x = y;
y = t;
}
if(strcmp(y,z)>0)
{
t = y;
y = z;
z = t;
}
if(strcmp(x,y)>0)
{
t = x;
x = y;
y = t;
}
puts(x);
puts(y);
puts(z);
return 0;
}

猜你喜欢

转载自www.cnblogs.com/jun-ruo-sui-nian/p/diary_006.html