您的位置:首页 > 其它

二级指针的使用情况

2014-02-24 21:51 239 查看
一、用二级指针作为函数参数,有两种典型情况:
1.需要传递一级指针的数组时:
例如标准 C 的 main 函数:
int main(int argc, char*[] argv),数组最高维可以退化,char*[] argv 等价于 char** argv。这里
argv 代表命令行参数数组。
2.需要对传入的一级指针进行修改时:
例如:
void alloc_new_char_array(int n, char** t)
{
*t = (char*)malloc(n * sizeof(t));
}
这里可以通过返回值达到相同的效果,不过需要同时修改多个指针的时候就不能用返回值
了。另外,C++中可以用引用代替,本质上和这里的修改指针的方法相同。
----
类似地,一级指针作为参数则用来传递非指针数组,以及对非指针对象进行修改。

******************************************************************************
******************************************************************************
补充二、指针用作传出参数时,需要二级指针
注意指针所指向的内存是在函数内分配的还是在函数外分配的,以及是不是在堆上分配的。
你定义了一个指针,但是并没有分配指针指向对象所需的内存空间;当函数返回后,此函数
栈中的内存会被释放掉,不要让指针指向此函数栈中的内存空间;要指向堆上或此函数外的
内存空间

实例1

#include <stdio.h>
#include <string.h>
char *ab(void);
void ak(char **ret);
void ac(char *ret);
int main()
{
char havec[] = "this is a b c d";
char **ret; // Alloc memory for secondary pointer
char *tmp;  // Alloc memory for first pointer
ret = &tmp; // this is imporint, why?
ak(ret);
printf("%s\n",tmp); // Ok
tmp = ab();
printf("%s\n",tmp); // Ok
ac(havec);
printf("havec = %s\n",havec);
return 0;
}
void ak(char **ret) // output argument, memory is alloced in the function
{
static char aa[] = "this is output argument";
*ret = aa;
}
void ac(char *ret) // memory is alloced outside the function
{
char *tmp;
if((tmp = index(ret,'c')) ==NULL) // this is just a example
return ;
*tmp = '\0';
}
char *ab(void) // return a pointer, memory is alloced in global
{
return "this is return value";
}

实例2

#include <stdio.h>
int main()
{
char *ret;
ak(ret);
return 0;
}
int ak(char *ret)
{
static char aa[] = "abc";ret = aa; // This ret is only a copy of the original ret
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息