06_1两次调用

/*
    两次调用的作用:
    第一次是获取字符串的长度
    第二次是跟据第一次获取的长度分配内存
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int getMem(char *p, char *meml, int *len)
{
    char *str = "hello world";
    len = strlen(str);
    if (meml != NULL)
    {   
        memcpy(meml, str, len);
    }
    return 0;
}

int main()
{
    int len = 0;
    char *p = NULL;
    //第一次调用数获取字符串长度
    getMem("aaa", NULL, &len);

    //根据长度分配内存
    p = (char *)malloc(len + 1);
    if(NULL == p){
        printf("malloc failed\n");
        return -1;  
    }
    memset(p, 0, len + 1);
    //第二次在进行拷贝
    getMem("aaa", p, &len);

    printf("p = %s\n", p);

    if(p != NULL){
        free(p);    
    }
}

猜你喜欢

转载自blog.csdn.net/WUZHU2017/article/details/81867647
今日推荐