gpt4 book ai didi

c - C 中 strcat() 的段错误

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

// Processes the array, starting from the second element
int j, k;
char *doubled;
for (j = 1; j < 500; j++) {
strcpy(doubled, output[j]);
strcat(doubled, doubled);
for (k = 0; k < j; k++) {
if (strcmp(output[k], output[j]) == 0) {
output[j] = doubled;
}
if (strcmp(output[k], doubled) == 0) {
output[j] = '\0';
}
}
}

尝试处理一个字符串数组,每当一个特定字符串出现两次时,第二次出现就会打印该字符串的重复项(例如dogdog --->dogdogdog),并且如果a出现两次以上字符串,删除该字符串(例如dogdogdog--->dogdogdog)。

我尝试调试,发现问题出在这段代码中,我不断收到段错误报告。

我需要做什么来解决这个问题?我已经研究了 strcat() 创建段错误的几种解决方案,但似乎没有一个真正有效。

最佳答案

编辑:根据注释,如果原始 cstrings 数组没有为每个字符串分配足够的内存,那么最好的解决方案可能是构造另一个空数组,每个字符串分配的内存是两倍,然后将旧数组复制到新的空的如下:

int count = 500;
int temp_size = 0;
char** new_array = malloc(count * sizeof(char*));
for(int i = 0; i < count; i++) {
temp_size = strlen(output[i]);
new_array[i] = malloc(((temp_size * 2) + 2) * sizeof(char)));
strcpy(new_array[i], output[i]);
}

Dynamically create an array of strings with malloc

通过在f​​or循环内声明变量可以避免很多麻烦,然后它们的生命周期和作用域就被限制在for循环内。就您而言,我认为这有效(请参阅评论和编辑):

int size = 0;
for (j = 1; j < count; j++) {
size = strlen(output[j]); //get the size of output[j]
char doubled[(size * 2) + 1]; //make cstring twice size + space for '\0'
strcpy(doubled, output[j]); //put one copy in the temporary buffer
strcat(doubled, output[j]); //concatenate next copy like this
for (k = 0; k < j; k++) {
if (strcmp(output[k], output[j]) == 0) {
strcpy(new_array[j], doubled); //make changes to new_array
}
if (strcmp(new_array[k], doubled) == 0) {
char deleted[1] = "\0"; //needed for free to work
strcpy(new_array[j], deleted); //otherwise runtime error
}
}
}

Declaring variables inside loops, good practice or bad practice?

完成new_array后,它也需要被删除:

for (int i = 0; i < count, i++) {
free(new_array[i]);
}
free(new_array);
new_array = NULL;

关于c - C 中 strcat() 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58652441/

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