#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; }