gpt4 book ai didi

c - Kochan InsertString 段错误

转载 作者:行者123 更新时间:2023-11-30 16:51:01 24 4
gpt4 key购买 nike

我正在学习 Kochan 的 C 编程书籍,并且正在做一项练习,该练习需要一个函数将一个字符串插入另一个字符串中,函数调用包括要插入字符串的位置。

我已经编写了以下代码,但每当我输入输入时,我都会收到段错误。我认为这是因为“输入”字符串被定义为用户输入的长度,然后 insertString 函数尝试向该字符串添加其他字符。我只是看不到一种将字符串定义得足够大以能够容纳额外字符的方法。您认为这就是我收到段错误的原因吗?还有其他方法可以解决这个问题吗?

#include<stdio.h>
#include <string.h>


insertString(char input[], const char insert[], int position)
{
int i, j;
char temp[81];

j = strlen(input);

for(i = 0; i < position - 1; i++)
{
temp[i] = input[i];
}

for(j = 0; insert != '\0'; i++, j++)
{
temp[i] = insert[j];
}

for(j = i - j; input != '\0'; i++, j++)
{
temp[i] = input[j];
}

for(i = 0; temp[i] != '\0'; i++)
{
input[i] = temp[i];
}

input[i] = '\0';
}

void readLine(char buffer[])
{
char character;
int i = 0;

do
{
character = getchar();
buffer[i] = character;
i++;
}
while(character != '\n');

buffer[i - 1] = '\0';
}

int main(void)
{
char input[81];
char insert[81];
int position;

printf("Enter the first string: ");
readLine(input);

printf("Enter the insert string: ");
readLine(insert);

printf("Enter placement position int: ");
scanf("%i", &position);

insertString(input, insert, position);

printf("The adjusted string is %s\n", input);

return 0;
}

最佳答案

也可能有其他原因,但以下片段肯定会崩溃:

for(j = 0; insert != '\0'; i++, j++)
{
temp[i] = insert[j];
}

原因是 - 由于 insert 不会被增加或操作 - 这是一个无限循环将“无限期”长写入 temp。一旦超过其长度80(或稍后),它将崩溃。我想您的意思是 for(j = 0; insert[j] != '\0'; i++, j++),对吗?

关于c - Kochan InsertString 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924448/

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