c中字符数组的串联 [英] concatenation of character arrays in c
本文介绍了c中字符数组的串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试连接2个字符数组,但是当我尝试连接两个字符数组时,我的o / p控制台挂起并且不打印任何内容。
I am trying to concatenate 2 character arrays but when I try it does not work and my o/p console hangs and does not print anything.
char *str[2];
str[0] = "Hello ";
str[1] = "World";
strcat(str[0],str[1]);
printf("%s\n",str[0]);
我什至尝试了下面的代码,但同样失败了
I even tried the below code which fails as well
char *str1 = "Hello ";
char *str2 = "World";
strcat(str1,str2);
printf("%s\n",str1);
有人可以解释吗?
TIA 。
推荐答案
此代码说明了问题:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *str1 = "Hello ";
char *str2 = "World";
char *ptr1, *ptr2;
printf("Find the end of str1...\n");
ptr1 = str1;
while (ptr1[0] != '\0') {
ptr1++;
}
printf("Copy str2 to the end of str1...\n");
ptr2 = str2;
while (ptr2[0] != '\0') {
printf("Attempt to write to read-only memory...\n");
ptr1[0] = ptr2[0];
printf("We never get here.\n");
ptr1++;
ptr2++;
}
ptr2[0] = '\0';
printf("Done.\n");
return 0;
}
输出
Find the end of str1...
Copy str2 to the end of str1...
Attempt to write to read-only memory...
Bus error: 10
这篇关于c中字符数组的串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文