gpt4 book ai didi

c - fprint 无法打印由函数返回的指针引用的串联字符串

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

我有以下程序:

#include <stdio.h>

#define MAXLEN 100

char *my_strcat(char *strp1,char *strp2) {

char str[MAXLEN], *strp;
strp = str;
while (*strp1 != '\0') {
*strp++ = *strp1++;
}
while (*strp2 != '\0') {
*strp++ = *strp2++;
}
*strp = '\0';
strp = str;
return strp;
}

void test_strcat(void) {

char *strp1, *strp2, *strp3, str1[MAXLEN], str2[MAXLEN];
printf("Testing strcat! Give two strings:\n");
gets_s(str1, sizeof(str1));
gets_s(str2, sizeof(str2));
strp1 = str1;
strp2 = str2;
strp3 = my_strcat(strp1, strp2);
printf("Concatenated string: %s", strp3);

}


int main(void) {
test_strcat();
}

函数 char *mystrcat 应该连接两个字符串,我用它来测试它test_strcat。程序运行时没有错误,但没有打印连接的字符串,而是打印笑脸符号。我已经通过调试完成了该程序,并且它看起来 my_strcat 发回的结果是正确的字符串。然而,当进入应该打印 strp3 的最后一行,它在调试工具,意味着它的值即将改变。 printf 调用后,strp3不再指向连接的字符串。有人知道什么可能导致此错误吗?

最佳答案

问题是这样的:

char str[MAXLEN], *strp;
strp = str; // str is a local variable
...
return strp; // <<== WRONG!!!

由于str是一个局部变量,一旦返回就会消失,因此strp指向的值在调用者取回控制权的实例后变得无效。

使用malloc而不是在自动存储区域(即堆栈上)分配内存将解决此问题:

char *str = malloc(strlen(strp1)+strlen(strp2)+1);
char *strp = str;

关于c - fprint 无法打印由函数返回的指针引用的串联字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24205158/

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