#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *catstr(char * s1,char * s2);
int main(){
char s1[] = "123456";
char s2[] = "67890";
char *str = NULL;
printf("before:str = 0x%x\n",str);
str = catstr(s1,s2);
printf("after:str = 0x%x\n",str);
printf("%s",str);
free(str); //将malloc分配的存储空间释放掉
return 0;
}
char *catstr(char * s1,char * s2){
char * str, *p;
int length = strlen(s1) + strlen(s2) +1;
//长度加1是为了存放'\0'
str = (char *) malloc(length * sizeof(char));
memset(str,0,length * sizeof (char));
p = str; //p指针和str指针同时指向分配的连续存储空间的首元素
while(*s1){
*p++ = *s1++;
//等价于 *p = *s1; p++ ; s1++;
}
while(*s2){
*p++ = *s2++;
//等价于 *p = *s2; p++ ; s2++;
}
return str;
}
问题:str = (char ) malloc(length * sizeof(char))的作用是什么? 为什么在子函数要再定义一个p去操作而不能去操作str或者直接返回p?