|
|
|
|
|
 Re: 指向指针的指针实例 - bbwolf [ 2005-06-26 10:51 | 134 byte(s)]
 Re: 指向指针的指针实例 - z_york [ 2005-06-27 18:02 | 159 byte(s)]
 Re: 指向指针的指针实例 - chong2 [ 2005-06-28 12:58 | 28 byte(s)]
 Re: 指向指针的指针实例 - beatit [ 2005-06-25 00:38 | 96 byte(s)]
|
|
|
|
[Original]
[Print]
[Top]
|
先看一个例子:
#include <stdio.h>
char buf[10] = "hello";
void pro(char *out)
{
out = buf;
}
main()
{
char *p = NULL;
pro(p);
printf("%s
", p);
}
我们想在函数pro()中改变指针p的值(记住:是指针p的值,而不是p所指向的地址的值)。能实现吗?
结果是不能,为什么?我们来分析一下。
如果不用函数pro(),我们可以直接在主函数中用 p = buf 来实现。如果使用函数pro(),就变得稍微复杂了。
因为我们要在函数pro()中改变指针p的值,而函数pro()又没有返回值,如何记住这个改变呢?
我们可以先用简单的例子说明:
#include <stdio.h>
void pro(char *out)
{
out[1] = 'o';
}
main()
{
char *p = "hello";
pro(p);
printf("%s
", p);
}
这个例子是改变了字符串指针p所指向的字符串的指,它能记住这个改变是因为在函数中是对指针所指向的地址
空间进行操作。你明白了吗?也就是说,函数的参数是char *out,我们可以改变 *out,但改变不了out本身。
所以针对第一个例子,我们要想改变p,必须把&p当作参数传给函数pro()。修改后的例子如下:
#include <stdio.h>
char buf[10] = "hello";
void pro(char **out)
{
*out = buf;
}
main()
{
char *p = NULL;
pro(&p);
printf("%s
", p);
}
|
|
|
----
对爱情要象对烹饪一样100%的投入
|
|
[Original]
[Print]
[Top]
|
|
[Original]
[Print]
[Top]
|
就是。
这本来就是C语言的基础问题,你弄不懂,应该找书来看,弄懂了,也无必要发帖告诉大家,我们都懂,这个问题不是问题,没有讨论价值。
|
|
|
----
I love David Beckham and Man.Utd. for ever.
|
|
[Original]
[Print]
[Top]
|
|
|