1. 程式人生 > >C 二級指標和三級指標的使用

C 二級指標和三級指標的使用

//這裡給出三級指標作為引數和二級指標作為引數的demo
//三級指正作為引數,記憶體分配在函式內
//二級指標作為引數,記憶體分配在函式外,也就是呼叫的地方
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include <iostream>
#include <string>
#include <vector>
using namespace std;


void func(char*** args, int &c)
{
    int count = 3;
    c = count;
    const char *iface[] = {"getStatus", "setStatus", "getUserName"};
    *args = (char**)malloc(count*sizeof(char*));
    for( int i = 0; i < count; i++ )
    {
        cout << iface[i] << endl;
        int len = strlen(iface[i])+1;
        (*args)[i] = (char*)malloc(len*sizeof(char));
        memset((*args)[i], 0, len);
        strcpy((*args)[i], iface[i]);
    }
}

void func2(char**args, int &num, int* lens)
{
    int count = 3;
    const char *iface[] = {"getStatus", "setStatus", "getUserName"};

    num = count;
    for( int i = 0; i < count; i++ )
    {
        lens[i] = strlen(iface[i]);
    }

    if( args == NULL )
        return;

    for( int i = 0; i < count; i++ )
    {
        strcpy(args[i], iface[i]);
    }
}

int main()
{
    char **array = NULL;
    int count = -1;
    func(&array, count);

    vector<string> ifaceList;
    cout << "count = " << count << endl;
    for( int i = 0; i < count; i++ )
    {
        cout << array[i] << endl;
        ifaceList.push_back(array[i]);
        if( array[i] != NULL )
        {
            free(array[i]);
            array[i] = NULL;
        }
    }

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

    cout << "----------------" << endl;
    for( vector<string>::iterator iter = ifaceList.begin(); iter != ifaceList.end(); iter++ )
    {
        cout << *iter << endl;
    }

    cout << "======= who allocate who free ==========" << endl;
    char** pIfaceList = NULL;
    int num = -1;
    int lens[100] = {-1};
    func2(pIfaceList, num, lens);
    cout << "num = " << num << endl;
    for( int i = 0; i < num; i++ )
    {
        cout << "len[" << i << "] = " << lens[i] << endl;
    }
    //allocate memory
    pIfaceList = (char**)malloc(num*sizeof(char*));
    for(int i = 0 ; i < num; i++)
    {
        int nLen = lens[i]+1;
        pIfaceList[i] = (char*)malloc(sizeof(char)*nLen);
        memset(pIfaceList[i], 0, sizeof(char)*nLen);
    }
    func2(pIfaceList, num, lens);
    vector<string> ifaceList2;
    for( int i = 0; i < num; i++ )
    {
        cout << "pIfaceList[" << i << "] = " << pIfaceList[i] << endl;
        ifaceList2.push_back(pIfaceList[i]);
        free(pIfaceList[i]);
        pIfaceList[i] = NULL;
    }
    if( pIfaceList != NULL )
    {
        free(pIfaceList);
        pIfaceList = NULL;
    }

    return 0;
}