在C中将指向函数的指针作为只读方式传递
正如标题所说,我可以传递指向函数的指针,因此它只是指针内容的副本吗? 我必须确保该function不会编辑内容。
非常感谢你。
我必须确保该function不会编辑内容
除非函数采用const
参数,否则您唯一能做的就是明确地传递一份数据副本,可能是使用memcpy
创建的。
你可以使用const
void foo(const char * pc)
这里pc
是指向const char的指针,通过使用pc
你无法编辑内容。
但它并不能保证您无法更改内容,因为通过创建指向相同内容的另一个指针,您可以修改内容。
所以,这取决于你,你将如何实现它。
是,
void function(int* const ptr){ int i; // ptr = &i wrong expression, will generate error ptr is constant; i = *ptr; // will not error as ptr is read only //*ptr=10; is correct } int main(){ int i=0; int *ptr =&i; function(ptr); }
在void function(int* const ptr)
ptr是常量但ptr指向的不是常量,因此*ptr=10
是正确的表达式!
void Foo( int * ptr, int const * ptrToConst, int * const constPtr, int const * const constPtrToConst ) { *ptr = 0; // OK: modifies the "pointee" data ptr = 0; // OK: modifies the pointer *ptrToConst = 0; // Error! Cannot modify the "pointee" data ptrToConst = 0; // OK: modifies the pointer *constPtr = 0; // OK: modifies the "pointee" data constPtr = 0; // Error! Cannot modify the pointer *constPtrToConst = 0; // Error! Cannot modify the "pointee" data constPtrToConst = 0; // Error! Cannot modify the pointer }
在这里学习!
我必须确保该function不会编辑内容。
什么内容? 指针指向的值? 在这种情况下,您可以声明您的function
void function(const int *ptr);
那么function()
不能改变ptr指向的整数。
如果你只是想确保ptr
本身没有改变,不要担心:它是通过值传递的(就像C中的所有内容一样),所以即使函数改变了它的ptr
参数,也不会影响传入的指针。