关于两个字符串的连接问题,,我写了一个程序,总是上机不对!!!请指教!!!不用STRCAT函数!!!

来源:百度知道 编辑:UC知道 时间:2024/06/05 03:00:40
#include<stdio.h>
#include<string.h>
main()
{
char a[]={'t','e','s','t'};
char b[]={'w','o','r','k','s'};
char c[10];
int i,j;
for(i=0;a[i]!='\0';i++)
c[i]=a[i];
for(j=0;b[j]!='\0';j++)
c[i+j]=b[j];
printf("%s\n",c);
}

你没有搞清楚字符数组与字符串的区别:
字符数组和其它数组一样,只是其元素是字符而已,比如你的
char a[] = {'t','e','s','t'};
就是一个四元数组,其四个元素就是t,e,s,t.没有'\0'!!
而字符串是由字符连接成的串,这些字符在内存中是在一起的.最后一个字符必为'\0'!也就是说 char * a="test";
中的"test"就是字符串,在t的后面会有一个'\0'.a是字符指针,它指向"test"的首地址,也就是字符't'的地址.
不知详细否?
顺便把程序附上,是在你的程序的基础上稍改了一下,可能不符你的要求,权作解释之用:
#include<stdio.h>
#include<string.h>
main() {
// char a[]={'t','e','s','t'};
// char b[]={'w','o','r','k','s'};
char *a = "test";
char *b = "works";
char c[10];
int i,j;
for(i=0;a[i]!='\0';i++) {
// printf("%c",a[i]);
c[i]=a[i];
}
// printf("\n");
for(j=0;b[j]!='\0';j++)
c[i+j]=b[j];
c[i+j] = '\0';<