标签:c提高 6 指针杂项 api函数封装 sockets封装 内存泄漏检测 日志库
指针杂项演示:
同一个函数分两次调用,执行不同的功能:
1,基本操作,被调函数分配内存
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getcontentlen(char *filename,char **buf,int *len)
{
        char *tmp = (char*)malloc(100);
        if(tmp == NULL) return -1;
        strcpy(tmp,"Hello!");
        *len = strlen(tmp);
        *buf = tmp;
        return 0;
}
int main()
{
        int ret = 0;
        char *filename = "myfile.txt";
        char *buf = NULL;
        int len = 0;
        ret = getcontentlen(filename,&buf,&len);
        if(ret != 0){return ret;}
        printf("%s \n",buf);
        printf("%d \n",len);
        
        if(buf != NULL) free(buf);
        return 0;
}
编译运行:
chunli@Linux:~/high$ gcc -g -o run main.c && ./run 
Hello! 
6 
chunli@Linux:~/high$#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getcontentlen(char *filename,char *buf,int *len)
{
        if(buf == NULL) 
        {
                *len = 10;
                return 0;
        }
        else
        {
                strncpy(buf,"Goog morning!",10);
        }
        return 0;
}
int main()
{
        int ret = 0;
        char *filename = "myfile.txt";
        int len = 0;
        ret = getcontentlen(filename,NULL,&len);
        char *buf = (char *)malloc(100);
        ret = getcontentlen(filename,buf,&len);
        printf("%s \n",buf);
        return 0;
}
编译:
chunli@Linux:~/high$ gcc -g -o run main.c && ./run 
Goog morni 
chunli@Linux:~/high$本文出自 “魂斗罗” 博客,请务必保留此出处http://990487026.blog.51cto.com/10133282/1792292
C提高 6 指针杂项 API函数封装,sockets封装 ,内存泄漏检测,日志库
标签:c提高 6 指针杂项 api函数封装 sockets封装 内存泄漏检测 日志库
原文地址:http://990487026.blog.51cto.com/10133282/1792292