且构网

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

指针作为 C 中的函数参数

更新时间:2023-11-13 14:14:58

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

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)

当按值传递时,你会得到一个值的副本.如果您更改函数中的值,无论您如何更改,调用者仍会看到原始值.

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)

通过指针为您提供指针的副本——它指向与原始指针相同的内存位置.该内存位置是存储原件的位置.这使您可以更改指向的值.但是,您无法更改指向数据的实际指针,因为您只收到了该指针的副本.

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)

您可以通过传递指向值的指针的指针来解决上述问题.如上所述,您可以更改该值,以便调用者可以看到更改,因为它与调用者代码使用的内存位置相同.出于同样的原因,您可以更改指向该值的指针.这让你可以在函数内分配内存并返回它;&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.