C语言——接口设计原则

来源:互联网 发布:javascript异步编程 编辑:程序博客网 时间:2024/06/05 02:14

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

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