现在的位置: 首页 > 综合 > 正文

指针参数传递

2013年02月16日 ⁄ 综合 ⁄ 共 1206字 ⁄ 字号 评论关闭

----字符串传递1
void test(char *p1)
{
 strcpy(p1,"hell");
   //不能使用p1 = "hello",这样会造成类型不匹配
}

int main()

 char a[12];
 test((char *)a);
    cout << a << endl;
 return 0;
}

-----方法2
void test(char* &p1)
{
 strcpy(p1,"hell");
}

int main()

    char *p1 = new char[20];//也可以在这里只分配,也可以在函数体内部释放
 test(p1);
    cout << p1 << endl;
    delete [] p1;
 return 0;
}

---方法3
void test(char **p1)
{
        //重新分配内存,因为原来的内存不够大,
        //最好作测试看函数调用者有无free或者delete
        //只要将*p1 = "hello" 字符串常量给它,看是否出错即可
 *p1 = new char[12];
 strcpy(*p1,"hell");
}

int main()

    char *p1 = NULL;
 test(&p1);
 cout << p1 << endl;
 delete [] p1;    //这里应释放p1,因为它指向堆内存
 return 0;
}

---以下是错误的,因为在函数体内改变p1本身的值,不会影响实参p1本身的值
static char a[100];

void test(char *p1)
{
 strcpy(a,"hell");
 p1 = a;
}

int main()

 printf("%x/n",a);
 char *p1 = NULL;
 test(p1);
 printf("%x/n",p1);
 //cout << p1 << endl;
 return 0;
}

--方法4
static char a[100];

char *test()
{
 strcpy(a,"hell");
 return a;
}

int main()

 char *p1 = test();
 cout << p1 <<endl;
 return 0;
}

--方法5
char *test()
{
 char *p = new char[10];
 strcpy(p,"hello");
 return p;
}

int main()

    char *p1 = test();
 cout << p1 << endl;
 delete [] p1;    //这里应释放p1,因为它指向堆内存
 return 0;
}

如果函数及调用者都是一个人,那上述这些程序都没问题,但是如果函数和调用者是不同的人写的,
那么一定要写说明如何调用(包括大小,是否需要释放等),如果不说明,最好使用第一种方法(当然有长度问题)
因为使用这种方法只能使用字符串数组来传递,而且不需要释放堆内存。

调用其他人的这些类型的函数,一定要注意是否需要释放堆内存
自已写的这些类型的函数供其它调用,一定要写明如何调用。

抱歉!评论已关闭.