在C中将指向函数的指针作为只读方式传递

Joh*_*ite 5 c pointers function readonly

正如标题所说,我可以传递指向函数的指针,因此它只是指针内容的副本吗?我必须确保该功能不会编辑内容.

非常感谢你.

Gri*_*han 7

是的,

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);

}
Run Code Online (Sandbox Code Playgroud)

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
} 
Run Code Online (Sandbox Code Playgroud)

在这里学习!


Omk*_*ant 6

您可以使用 const

void foo(const char * pc)

这里pc是指向const char的指针,通过使用pc你无法编辑内容.

但它并不保证您无法更改内容,因为通过创建指向相同内容的另一个指针,您可以修改内容.

所以,这取决于你,你将如何实现它.


cni*_*tar 3

我必须确保该功能不会编辑内容

除非该函数采用const参数,否则您唯一能做的就是显式向其传递数据的副本,可能是使用memcpy.

  • @DanielS如果它创建一个非常量指针并使其指向常量指针的内容,那么它就会进入未定义行为区域。即它是无效代码。 (2认同)