函数多个返回值(返回多个参数/局部变量)通过双重指针来实现

2014-11-23 21:58:42 · 作者: · 浏览: 8
测试用例:
// DoublePTest.cpp : 定义控制台应用程序的入口点。  
//  
  
#include "stdafx.h"  
#include //malloc需要的头文件  
#include "cstring"//memset需要的头文件  
  
using namespace std;  
void Func(char** p)  
{  
    *p = (char*)malloc(3);  
    char* c = new char[3];  
    memset(c, 'a', 3);  
    //c[3]='\0';   //if there is open,below delete is wrong  
    memcpy(*p, c, 3);  
    delete c;  
    c=NULL;  
}  
int _tmain(int argc, _TCHAR* argv[])  
{  
    char *p = NULL;  
    Func(&p);  
    if(p)  
    {  
        char *sp =p;  
        int len= strlen(sp);  
        delete p;  
        p = NULL;  
    }  
    return 0;  
}  
  

这里的测试代码只是测试返回一个指针类型的变量,比如字符串或者是内存中的一块buffer,当然返回一般的参数或者一般的局部变量的值通过引用就可以实现。