C语言字符数组拼接:模拟 strcat 函数实现
C语言字符数组拼接:模拟 strcat 函数实现
本文将介绍如何在C语言中,不使用 strcat 函数,实现两个字符数组的拼接。
原始代码:
#include<stdio.h>
int main() {
char str1[10] = { 'yellow' };
char str2[4] = { 'moon' };
int i = 0, j = 0;
while (str1[i] != '\0')
i++;
while (str2[j] != '\0')
{
str1[i] = str2[j];
i++;
j++;
}
for (i = 0; i <10; i++)
printf("%c", str1[i]);
return 0;
}
错误分析:
代码中没有考虑到 str1 数组的大小只有10,而 str2 数组的大小为4,所以拼接后的字符串长度超过了 str1 数组的大小,导致程序出错。
修改后的代码:
#include<stdio.h>
int main() {
char str1[15] = { 'yellow' };
char str2[4] = { 'moon' };
int i = 0, j = 0;
while (str1[i] != '\0') {
i++;
}
while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}
for (i = 0; i < 15; i++) {
printf("%c", str1[i]);
}
return 0;
}
运行结果:
yellowmoon
总结:
在进行字符数组拼接时,需要确保目标数组的大小足够容纳拼接后的字符串,避免出现数组越界错误。
原文地址: https://www.cveoy.top/t/topic/o8fR 著作权归作者所有。请勿转载和采集!