这个问题记得以前已经谈论这个问题,再来简单的说一下:
如果是在一个作用域里面,就是直接改变他的指向就可以了,比如重新分配一个地址空间。或者指向另外一个地址空间。
这个很简单,就不说了。
如果要在另外一个函数里面来改变一个地址空间呢?
两种方法,一种是使用指针参数改变,另一种是return方法!
那么就要使用多一级指针,如果是2重指针,就要使用3重指针,同时在这个函数里面,分配指针的时候一定要以一个指针带指针名为单位进行地址的分配。
其实就是这样 int **p;
void converse(int ***p, int x, int y) 当传入值的时候,用p的地址传入&p,那么进入函数后,加上一个*后
*&P其实就是p了,那么就跟在一个作用域里面一样了哦。
另外一种就是用同级指针,但是必须使用返回,而且调用的时候传值必须要初始化,我们一般的初始化为null。
下面给一个程序综合上面两种方法:
#
include <stdio.h>
#include <malloc.h>
int
***
GetMemory(
int
***
p
,
int
x
,
int
y)
{
p
=
(
int
***
)malloc(
10
);
for
(
int
i
=
0
; i
<
10
; i
++
) {
p[i]
=
(
int
**
)malloc(x);
for
(
int
j
=
0
; j
<
x; j
++
)
p[i][j]
=
(
int
*
)malloc(y);
}
return
p;
}
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
void converse(
int
***
p
,
int
x
,
int
y) {
*
p
=
(
int
**
)malloc(x);
for
(
int
j
=
0
; j
<
x; j
++
) {
(
*
p)[j]
=
(
int
*
)malloc(y);
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
int
main()
{
int
***
p
=
NULL;
p
=
GetMemory(p
,
3
,
5
);
//
p[
2
]
=
0
;
//
下面就可以使用p了
p[
0
][
1
][
1
]
=
1
;
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
int
**
q;
converse(
&
q
,
3
,
5
);
q[
1
][
1
]
=
1
;
return
0
;
}