C语言——接口设计原则

本文详细解析了C语言中接口设计的重要性,并通过具体实例展示了如何利用函数参数指针来实现一个函数具有多个输出,提高代码复用性和功能性。此外,文章还介绍了函数返回值在异常提示和链式编程中的应用,以及如何通过定义宏和包含常用头文件优化代码。最后,通过一个实际的内存分配示例,演示了如何在C语言中安全地分配和释放内存资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值