#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> //指针做输出,被调用函数分配内存 √ //指针做输入,主调函数分配内存 //求两段话的长度 int getNum(char **myp1,int *mylen1,char **myp2,int *mylen2) { int ret = 0; char *tmp1 = NULL; char *tmp2 = NULL; tmp1 = (char *)malloc(100); if (tmp1 == NULL) { return -1; } tmp1 = strcpy(tmp1, "abcdefg"); *mylen1 = strlen(tmp1); *myp1 = tmp1; //间接修改实参p1的值 tmp2 = (char *)malloc(100); if (tmp2 == NULL) { return -2; } tmp2 = strcpy(tmp2, "11222"); *mylen2 = strlen(tmp2); *myp2 = tmp2; //间接修改实参p2的值 return ret; } int getNum_Free(char **myp1) { //if (myp1 == NULL) //{ // return; //} //free(*myp1); //释放完指针变量,所指的内存空间 //*myp1 = NULL; //把实参改成NULL //或者这么写 char *tmp; tmp = myp1; if (myp1 == NULL) { return -1; } tmp = *myp1; free(tmp); *myp1 = NULL; return 0; } int main() { char *p1=NULL, *p2=NULL; int len1 = 0,len2 = 0; int ret = 0; ret = getNum(&p1, &len1, &p2, &len2); if (!ret) { printf("p1:%s\n", p1); printf("p2:%s\n", p2); getNum_Free(&p1); getNum_Free(&p2); } else { printf("func getNum():%d", ret); } system("pause"); return 0; }
时间: 2024-12-16 10:12:39