主調函數中的指針所指向的內存空間可以在當前函數中直接分配,也可以在被調函數中分配,同樣可以二次調用被調函數,第一次讓被調函數返回一個內存空間的大小,然後在主調函數中根據被調函數返回的空間大小分配內存,第二次調用往主調函數分配的內存空間中寫入數據。這也是項目開發過程中會用到的一種內存分配方式,所以在這裏說明一下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int getMem(char* buf, int *len) {
int ret = 0;
char* temp = NULL;
//第一次調用返回內存空間大小
if (buf == NULL) {
*len = 10;
return ret;
//第二次調用返回向內存空間中寫入數據
else {
temp = (char*)malloc(1024);
if (temp == NULL) {
ret = -1;
printf("func getMem temp == NULL err : %d\n", ret);
return ret;
}
strcpy(temp, "hello world ORZ");
int templen = strlen(temp);
int strlen = (*len - 1) < templen ? (*len - 1) : templen;
strncpy(buf, temp, strlen);
buf[strlen] = '\0';
return ret;
}
}
int main(){
int ret = 0;
char* buf = NULL;
int len;
ret = getMem(NULL, &len);
if (ret != 0) {
printf("func getMem err : %d\n", ret);
}
buf = (char*)malloc(len);
if (buf == NULL) {
printf("memory err \n");
return -1;
}
ret = getMem(buf, &len);
if (ret != 0) {
printf("func getMem err : %d\n", ret);
free(buf);
return ret;
}
printf("buf : %s\n", buf);
if (buf != NULL) {
free(buf);
}
system("pause");
return 0;
}
輸出結果: