主调函数中的指针所指向的内存空间可以在当前函数中直接分配,也可以在被调函数中分配,同样可以二次调用被调函数,第一次让被调函数返回一个内存空间的大小,然后在主调函数中根据被调函数返回的空间大小分配内存,第二次调用往主调函数分配的内存空间中写入数据。这也是项目开发过程中会用到的一种内存分配方式,所以在这里说明一下:
#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;
}
输出结果: