主调函数分配内存的两次调用

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

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

输出结果:
这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值