求大神指点这个关于指针的问题

x122415199 2012-04-19 12:26:31
#include "stdio.h"
#include "string.h"
void main()
{void sort(char(*s)[20]);
int i;
char str[10][20];

for(i=0;i<10;i++)
scanf("%s",&str[i]);
sort(str);

for(i=0;i<10;i++)
printf("%s\n",str[i]);

}
void sort(char (*s)[20])
{
int i,j;
char *temp;

for(i=0;i<9;i++)
for(j=0;j<9-i;j++)
if(strcmp(s[j],s[j+1])>0)
{temp=*(s+j);*(s+j)=*(s+j+1);*(s+j+1)=temp;}
}
运行显示错误在最后一行,麻烦指点一下哪里错了,为什么?
...全文
158 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
evencoming 2012-04-19
  • 打赏
  • 举报
回复
*(s+j+1)=temp;
类似
int arr[10];
int *t;
arr=t;

主要是数组是不能被赋值的左值。
这里,改为 strcpy吧。
void sort(char (*s)[20])
{
int i,j;
char *temp;

for(i=0;i<9;i++)
for(j=0;j<9-i;j++)
if(strcmp(s[j],s[j+1])>0)
{temp=*(s+j);*(s+j)=*(s+j+1);*(s+j+1)=temp;}
}

==》
void sort(char (*s)[20])
{
int i,j;
char temp[20];

for(i=0;i<9;i++)
for(j=0;j<9-i;j++)
if(strcmp(s[j],s[j+1])>0)
{strcpy(temp,*(s+j));
strcpy(*(s+j),*(s+j+1));
strcpy(*(s+j+1),temp);
}
}
hen_hao_ji 2012-04-19
  • 打赏
  • 举报
回复
要用strcpy吧


void sort(char (*s)[20])
{
int i,j;
char temp[20];

for(i=0;i<9;i++)
for(j=0;j<9-i;j++)
if(strcmp(s[j],s[j+1])>0)
{
strcpy(temp,s[j]);
strcpy(s[j],s[j+1]);
strcpy(s[j+1],temp);
}
}

cauiot 2012-04-19
  • 打赏
  • 举报
回复
估计是数组越界
x122415199 2012-04-19
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

*(s+j+1)=temp;
类似
int arr[10];
int *t;
arr=t;

主要是数组是不能被赋值的左值。
这里,改为 strcpy吧。
void sort(char (*s)[20])
{
int i,j;
char *temp;

for(i=0;i<9;i++)
for(j=0;j<9-i;j++)
if(strcmp(s[j],s[j+1]……
[/Quote]正解,错误提示是英文,虽然看不太懂,但大意就是左值问题。
x122415199 2012-04-19
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

要用strcpy吧

C/C++ code

void sort(char (*s)[20])
{
int i,j;
char temp[20];

[/Quote]有道理的,定义*temp确实应该用strcpy函数
x122415199 2012-04-19
  • 打赏
  • 举报
回复
一觉醒来,忽然顿悟,贴上修改后源码,供各位大神讨论

#include "stdio.h"
#include "string.h"
void main()
{void sort(char(*s)[20]);
int i;
char str[10][20];
printf("input 10 string:\n");
for(i=0;i<10;i++)
scanf("%s",&str[i]);
sort(str);
printf("Now,The sequence is:\n");
for(i=0;i<10;i++)
printf("%s\n",str[i]);

}
void sort(char (*s)[20])
{
int i,j,k;
char temp;

for(i=0;i<9;i++)
for(k=0;k<9-i;k++)
if(strcmp(s[k],s[k+1])>0)
for(j=0;j<20;j++)
{
temp=*(*(s+k)+j);
*(*(s+k)+j)=*(*(s+k+1)+j);
*(*(s+k+1)+j)=temp;
}
}
newfarmerchi 2012-04-19
  • 打赏
  • 举报
回复

#include "stdio.h"
#include "string.h"
void sort(char*s[]);//传递的参数为指针数组
void main()
{
int i;
char str[10][20];
char *s[10];//定义指针数组

for(i=0;i<10;i++)
{
scanf("%s",&str[i]);
s[i]=str[i];//给指针数组赋值
}
sort(s);

for(i=0;i<10;i++)
printf("%s\n",s[i]);//打印指针数组的值

}
void sort(char *s[])
{
int i,j;
char *temp;

for(i=0;i<9;i++)
for(j=0;j<9-i;j++)
if(strcmp(s[j],s[j+1])>0)
{
temp=*(s+j);*(s+j)=*(s+j+1);*(s+j+1)=temp;
}
}






69,372

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧