指针作为C中的函数参数 [英] Pointers as function arguments in C

查看:73
本文介绍了指针作为C中的函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果要使用此代码,则:

If I were to have this code, for example:

int num = 5;
int *ptr = #

以下两个功能有什么区别?

What is the difference between the following two functions?

void func(int **foo);
void func(int *foo); 

我在哪里调用函数:

func(&ptr); 


我意识到,两者中的前者将指向指针的指针作为参数,而第二者仅接收指针.


I realize that the former of the two takes a pointer to a pointer as a parameter, while the second takes only a pointer.

如果传入func(&ptr),则实际上是传入了指针.指针指向另一个指针有什么区别?

If I pass in func(&ptr), I am effectively passing in a pointer. What difference does it make that the pointer points to another pointer?

我相信后者会发出不兼容警告,但似乎只要您知道自己在做什么,细节就无关紧要.似乎出于可读性和理解的原因,前者是一个更好的选择(2星指针),但是从逻辑的角度来看,有什么区别?

I believe the latter will give an incompatibility warning, but it seems that the details do not matter so long as you know what you are doing. It seems that perhaps for the sake of readability and understanding the former is a better option (2-star pointer), but from a logical standpoint, what is the difference?

推荐答案

一个合理的经验法则是,您不能完全更改传递的确切内容,即调用方可以看到更改.解决方法是传递指针.

A reasonable rule of thumb is that you can't exactly change the exact thing that is passed is such a way that the caller sees the change. Passing pointers is the workaround.

按值传递:void fcn(int foo)

Pass By Value: void fcn(int foo)

按值传递时,将获得该值的副本.如果您在函数中更改了值,则无论您进行的更改如何,调用方仍会看到原始值.

When passing by value, you get a copy of the value. If you change the value in your function, the caller still sees the original value regardless of your changes.

按指针传递值:void fcn(int* foo)

Pass By Pointer to Value: void fcn(int* foo)

通过指针传递给您指针的副本-它指向与原始指针相同的内存位置.该存储位置是存储原始文件的位置.这使您可以更改指向的值.但是,由于只收到了该指针的副本,因此无法更改实际的数据指针.

Passing by pointer gives you a copy of the pointer - it points to the same memory location as the original. This memory location is where the original is stored. This lets you change the pointed-to value. However, you can't change the actual pointer to the data since you only received a copy of the pointer.

将指针传递给指向值的指针:void fcn(int** foo)

Pass Pointer to Pointer to Value: void fcn(int** foo)

通过将指针传递给指向值的指针来解决上述问题.如上所述,您可以更改该值,以便调用者可以看到更改,因为它与调用者代码使用的存储位置相同.出于相同的原因,您可以将指针更改为该值.这样,您就可以执行以下操作:在函数内分配内存并返回它; &arg2 = calloc(len);.您仍然无法将指针更改为指针,因为那是您收到的副本.

You get around the above by passing a pointer to a pointer to a value. As above, you can change the value so that the caller will see the change because it's the same memory location as the caller code is using. For the same reason, you can change the pointer to the value. This lets you do such things as allocate memory within the function and return it; &arg2 = calloc(len);. You still can't change the pointer to the pointer, since that's the thing you recieve a copy of.

这篇关于指针作为C中的函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆