C语言——接口设计原则

接口的封装与设计尤为重要,一个好的接口应该是调用简单,功能强大。
一般的函数完成一个功能,因为函数只有一个返回值。
但可以通过指针做函数参数,使得一个函数具有多个输出,从而完成多个功能,而函数返回值则是用来提示此接口调用过程中异常行为。当然,函数返回值有时候为了支持链式编程而返回特定类型数据,就不能让其指示异常行为了。

#define _CRT_SECURE_NO_WARNINGS

#include "stdlib.h"
#include "stdio.h"
#include "string.h"


char* GetMemory_1()
{
    char* pAddr = (char*)malloc(100 * sizeof(char));
    return pAddr;
}
char* GetMemory_2(char* p,int size)
{
    p = (char*)malloc(size * sizeof(char));
    return p;
}

int  GetMemory_3(char** p, int size)
{
    int res = 0;
    if (p == NULL)
    {
        res = -1;
        return res;
    }
    *p = (char*)malloc(size * sizeof(char));
    return res;
}

int  GetMemory_4(char** p, int size)
{
    int res = 0;
    if (p == NULL)
    {
        res = -1;
        return res;
    }
    *p = (char*)malloc(size * sizeof(char));
    return res;
}

int GetHeapAddr(char** str, int len_1, char (*name)[10],int len_2,char *** p,int * num)
{
    int res = 0;
    int len = len_1 + len_2;
    if (str == NULL || name == NULL || p == NULL || num == NULL)
    {
        res = -2;
        return res;
    }

    char** temp = NULL;
    temp = (char**)malloc(sizeof(char*)*(len));

    for (int i = 0; i < len_1; i++)
    {
        temp[i] = (char*)malloc(sizeof(char)*(strlen(str[i]) + 1));
        if (temp[i] == NULL)
        {
            res = -1;
            return res;
        }
        strcpy(temp[i], str[i]);
    }

    for (int j = 0; j < len_2; j++)
    {
        temp[j + len_1] = (char*)malloc(sizeof(char)*(strlen(name[j]) + 1));
        if (temp[j + len_1] == NULL)
        {
            res = -1;
            return res;
        }

        strcpy(temp[j + len_1], name[j]);
    }

    *p = temp;
    *num = len;

    return res;

}
//释放二维内存模型资源,free二级指针,同时避免野指针,所以需要三级指针
int FreeMemory(char*** p,int len)
{
    int res = 0;
    char** temp = NULL;
    if (p == NULL)
    {
        res = -1;
        return res;
    }

    temp = *p;

    for (int i = 0; i < len; i++)
    {
        if (temp[i] != NULL)
        {
            free(temp[i]);
            temp[i] = NULL;
        }
    }

    free(temp);
    *p = NULL;//修改实参,二级指针的数值,避免野指针

    return res;
}

void main()
{
    char* str[] = { "aaaaa", "bbbbbbbbb", "cccccc" };

    char name[][10] = { "john", "wade", "howard" ,"james"};
    char **p = NULL;
    int num = 0;
    int res = GetHeapAddr(str, 3, name, 4, &p, &num);

    FreeMemory(&p,num); 

    system("pause");
}


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值