问:这个程序的错误在哪?

yinkhit1 2009-11-25 04:36:21
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include<string.h>
#include <ctype.h>
int main()
{
char * article[]={"the","a","one","some","any"};
char * noun[]={"boy","girl","dog","town","car"};
char * verb[]={"drove","jumped","ran","walked","skipped"};
char * preposition[]={"to","from","over","under","on"};
char * sentence;
srand(time(NULL));
sentence=strcat(article[rand()%5]," ");
sentence=strcat(sentence,noun[rand()%5]);
sentence=strcat(sentence," ");
sentence=strcat(sentence,verb[rand()%5]);
sentence=strcat(sentence," ");
sentence=strcat(sentence,preposition[rand()%5]);
sentence=strcat(sentence," ");
sentence=strcat(sentence,article[rand()%5]);
sentence=strcat(sentence," ");
sentence=strcat(sentence,noun[rand()%5]);
for(int i=1;i<=20;i++)
printf("%s",sentence);
return 0;
}
程序如上:目的是打印20个句子,可是有错误,为什么?
...全文
174 9 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
challenge99 2009-11-26
  • 打赏
  • 举报
回复
很简单的问题,先看看strcat说明.......
baoyiquan 2009-11-26
  • 打赏
  • 举报
回复
改成这样也可以:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
int main()
{
char * article[]={"the","a","one","some","any"};
char * noun[]={"boy","girl","dog","town","car"};
char * verb[]={"drove","jumped","ran","walked","skipped"};
char * preposition[]={"to","from","over","under","on"};
char * sentence = NULL;
int i = 0;
int lenth = 100 * sizeof(char);

sentence = (char *)malloc(lenth);
printf("%d\n",lenth);
memset(sentence,'0', lenth);
srand(time(NULL));

while(i++ < 20)
{
strcpy(sentence, article[rand()%5]);
sentence=strcat(sentence," ");
sentence=strcat(sentence,noun[rand()%5]);
sentence=strcat(sentence," ");
sentence=strcat(sentence,verb[rand()%5]);
sentence=strcat(sentence," ");
sentence=strcat(sentence,preposition[rand()%5]);
sentence=strcat(sentence," ");
sentence=strcat(sentence,article[rand()%5]);
sentence=strcat(sentence," ");
sentence=strcat(sentence,noun[rand()%5]);
printf("%d = %s\n",i, sentence);
}

free(sentence);

return 0;
}
yinkhit1 2009-11-25
  • 打赏
  • 举报
回复
5楼:我试了,还是不行啊。请您说清楚点,谢谢撒!
shenxf_1982 2009-11-25
  • 打赏
  • 举报
回复
静态常量字符串,不能修改得
pombo 2009-11-25
  • 打赏
  • 举报
回复
错误1:
sentence没有分配内存空间,并且一定要初始化

错误2:
sentence=strcat(article[rand()%5]," "); 有问题

article[]的内容在静态区域,不能更改的。
应该改成strcat(sentence," ");
ssssaaaa_aa 2009-11-25
  • 打赏
  • 举报
回复
challenge99:
分配空间后,运行时还是有错误.我试过了.
所以楼主还是检查一下strcat吧!
ssssaaaa_aa 2009-11-25
  • 打赏
  • 举报
回复
我决的这里的strcat(article[rand()%5]," ")和strcat(sentence,article[rand()%5])分别是"地址和字符"/"地址和地址"相联接;而并不是与字符指针所指向的内容相联接;所以运行时就会产生错误.

建议:
你先弄清字符指针数组在内存中存储字符串的形式和字符指针数组的引用规则或者用二维数组试试.
yexingzheLC 2009-11-25
  • 打赏
  • 举报
回复
LZ这个分啊,实在是令人失望!
challenge99 2009-11-25
  • 打赏
  • 举报
回复
没有分配空间,自然玩不动啦

sentence = malloc(100);

strcat(sentence, article ....
strcat(sentence, noun ...
.....

70,030

社区成员

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

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