且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

指针作为C中的函数参数

更新时间:2023-11-13 14:41:34

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

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.