改变函数中的指针,c [英] changing pointers in functions, c
问题描述
我会提前说我在询问指针的指针,所以我的话可能有点含糊,但尽量留在我身边:)
我试图了解更改作为参数传递的指针如何在函数范围之外生效.到目前为止,这是我的理解:如果将指针作为参数传递给函数,我只能更改指针指向的内容,而不能更改指针本身(我说的是将在作用域外生效的更改的功能,正如我所说).如果我想改变指针指向的东西,我必须传递一个指向指针的指针.
到目前为止我是对的吗?另外,我注意到当我有一个包含一些指针的结构时,如果我想初始化这些指针,我必须将 struct
作为指向指针的指针传递给初始化函数.这是出于同样的原因吗?
你说得对,但如果你已经分配了结构体,那么你可以传递一个指向它的指针.但是,如果函数分配了结构体,那么要么使用函数返回来收集新分配结构体的值,要么传入一个指向参数列表中的指针的指针.
(我手头没有 c 编译器,但我试着写了一些例子).
- 你已经分配了指针
- 分配指针的函数
- 分配指针的函数
I'll say in advance that I'm asking about pointers to pointers, so my words may be a bit vague, but try to stay with me :)
I am trying to understand how changing a pointer passed as an argument takes effect outside the scope of the function. So far this is what I understand: if a pointer is passed as an argument to a function, I can only change what the pointer points to, and not the pointer itself (I'm talking about a change that will take effect outside the scope of the function, as I said). And if I want to change what the pointer is pointing to, I have to pass a pointer to a pointer.
Am I right so far?
Also, I've noticed that when I have a struct that holds some pointers, if I want to initialize those pointers I have to pass the struct
to the initialization function as a pointer to pointer. Is this for the same reason?
You are right in the first bit but if you've allocated the struct then you can pass a pointer to it. However, if the function allocated the struct, then either you use the function return to collect the value of the newly allocated struct or you pass in a pointer to a pointer in the parameter list.
(I've not got a c compiler to hand but I've tried to write some examples).
- You've allocated the pointer
int main() { struct x *px = malloc(...); initx(px); } void intix(struct x* px){ px-> .... }
- The function allocated the pointer
int main() { struct x *px = initx(); } struct x* intix(){ struct x *px = malloc(...); px-> .... return px; }
- The function allocated the pointer
int main() { struct x *px; initx(&px); } void intix(struct x** ppx){ struct x *px = malloc(...); px-> .... *ppx = px; }
这篇关于改变函数中的指针,c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!