【发布时间】:2014-06-13 12:20:46
【问题描述】:
我有以下程序:
#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
不再指向连接的字符串。任何人都知道可能导致此错误的原因是什么?
【问题讨论】:
-
您正在返回一个局部变量。您需要使用
malloc而不是数组。char *strp = new char[MAXLEN]; -
什么是
str[MAXLEN]?它似乎未初始化,从未使用过,但它是您从函数返回的...strp = str; return strp; -
在
*my_strcat()函数中通过char *strp=(char *)malloc(MAXLEN*sizeof(char));尝试。