谁帮我看看,。。。C程序问题。

来源:百度知道 编辑:UC知道 时间:2024/09/20 23:26:29
#include"stdio.h"
void string_cat(char *x,char *y)
{
int i=0,j=0;
while(*(x+i)!='\0') i++;
while(*(y+i)!='\0')
{
*(x+i)=*(y+j);i++;j++;
}
*(x+i)='\0';
}
void main()
{
char str1[]="Chinese is better ",str2[]="than Japan!";
char *p1,*p2;
p1=&str1[0];p2=&str2[0];
printf("str1=%s\nstr2=%s\n",str1,str2);
printf("the new string is:");
string_cat(p1,p2);
printf("%s\n",p1);
}
这个程序有什么问题?
运行结果是对的
但是一运行就有错误说要关闭 或者需要调试。。。
可以加进去的
因为每次while循环 都在把str1的地址扩大。。。

while(*(y+i)!='\0') 的确应该是while(*(y+j)!='\0') ,这个估计是楼主打错了,不是问题关键。问题还是二楼所说,str1的空间太小,虽然str1的地址扩大,但超过了str1的长度后的加进来的字母就不算str1的内容了,而且造成str1不是以'\0'结尾,因为'\0'在str1之外了嘛。这样有的系统可以输出,有的就退出,这是个很大的安全隐患,绝对不好。
谭浩强说在字符串连接时,被连接的字符串要有足够的空间,所以问题很简单,就是把str1的容量扩大。更改如下,在win-tc和下Dev-c++下运行通过。
#include <stdio.h>
#include <conio.h>

void string_cat(char *x,char *y)
{
int i=0,j=0;
while(*(x+i)!='\0') i++;
while(*(y+j)!='\0')
{
*(x+i)=*(y+j);i++;j++;
}
*(x+i)='\0';
}

void main()
{
char str1[50]="Chinese is better ",str2[]="than Japan!";/*str1扩大空间*/
char *p1,*p2;
p1=&str1[0];p2=&str2[0]; /*或者p1=str1;p2=str2;*/
printf("str1=%s\nstr2=%s\n",str1,str2);
printf("the new string is:");
string_cat(p1,p2);
printf("%s\n",p1);