gpt4 book ai didi

c - 将两个字符串连接成一个时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:20 25 4
gpt4 key购买 nike

我需要编写一个程序,将两个字符串连接到第一个字符串中。我不能使用第三个参数来保存新字符串。当我运行该程序时,我没有得到任何输出,所以我很确定问题出在我连接两个字符串的函数中。

#include <stdio.h>

#define MAX_SZ 81

int concatString(char s1[], char s2[]); // concatenates s2 onto s1, returns length of s1
int getString(char c[], int len);

main(void)
{
char array1[MAX_SZ * 2];
char array2[MAX_SZ];
int string1 = 0;
int string2 = 0;
int concat = 0;

printf("Please String # 1 up to 80 characters long:\n");
string1 = getString(array1, MAX_SZ);
printf("Please enter String #2 up to 80 characters long:\n");
string2 = getString(array2, MAX_SZ);

concat = concatString(array1, array2);

printf("You entered \"%s\" (length = %i)\n", array1, concat);

return 0;
}

int getString(char c[], int len)
{
int i = 0;
char d = 0;
while (d != '\n' && i < len)
{
d = getchar();
c[i++] = d;
}

c[--i] = '\0';
return (i);
}

int concatString(char s1[], char s2[])
{
int i, j;

for (i = 0; s1 != '\0'; ++i)
s1[i] = s1[i];

for (j = i; s2 != '\0'; ++j)
s1[j] = s2[j];

s1 [i + j] = '\0';
return (i + j);
}

最佳答案

问题出在这几行:

for (j = i; s2 != '\0'; ++j)
s1[j] = s2[j];

此处 j 不为零,因此您开始在 s2 中的非零索引处进行索引,甚至可能超出范围。

但这只是一个问题。第二个问题是循环的条件,它永远不会为假导致无限循环。

第一个循环在循环条件上有同样的问题。

至于为什么 循环条件是错误的,字符'\0' 等于零,这在大多数系统上也等于NULL。因此,您正在有效地检查是否s1 != NULL。由于两个字符串都是编译时数组,因此传递给函数的指针永远不会是空指针。

关于c - 将两个字符串连接成一个时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38359407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com