给出一道错误案例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *fun1(char *s1, char *s2)
{
char rs[100] = {0};
int l1 = strlen(s1);
strcpy(rs, s1);
strcpy(rs + l1, s2);
return rs;
}//*fun1
int main()
{
char s1[10] = "Hello";
char s2[10] = " ";
char s3[10] = "World";
char *ps;
ps = fun1(s1, s2);
ps = fun1(ps, s3);
puts(ps);
return 0;
}
输出结果:
错误分析:
本道题目是对字符串进行一个拼接,理论上应该输出:
Hello World
原因在于:
rs为临时创建的数组,返回值为一个临时地址
在进行第二个调试ps时找不到之前所返回的rs也就是ps的地址
解决方法:
这时可以通过动态内存进行修改代码:
char *fun1(char *s1, char *s2) { // char rs[100] = {0}; char *rs = (char *)malloc(100); int l1 = strlen(s1); strcpy(rs, s1); strcpy(rs + l1, s2); return rs; }//*fun1
将要返回的rs指向申请的动态内存
(char *)malloc(100)变量类型为数组,返回值为指针
此时结果就正确了: