Pass a pointer to a function as read-only in C

后端 未结 4 335
北海茫月
北海茫月 2021-01-18 15:15

Just as the title says, can I pass a pointer to a function so it\'s only a copy of the pointer\'s contents? I have to be sure the function doesn\'t edit the contents.

<
相关标签:
4条回答
  • 2021-01-18 15:56

    You can use const

    void foo(const char * pc)

    here pc is pointer to const char and by using pc you can't edit the contents.

    But it doesn't guarantee that you can't change the contents, because by creating another pointer to same content you can modify the contents.

    So,It's up to you , how are you going to implement it.

    0 讨论(0)
  • 2021-01-18 15:56

    Yes,

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

    In void function(int* const ptr) ptr is constant but what ptr is pointing is not constant hence *ptr=10 is correct expression!


    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
    } 
    

    Learn here!

    0 讨论(0)
  • 2021-01-18 15:57

    I have to be sure the function doesn't edit the contents

    Unless the function takes a const parameter, the only thing you can do is explicitly pass it a copy of your data, perhaps created using memcpy.

    0 讨论(0)
  • 2021-01-18 16:06

    I have to be sure the function doesn't edit the contents.

    What contents? The value pointed to by the pointer? In this case, you can declare your function like

    void function(const int *ptr);
    

    then function() cannot change the integer pointed to by ptr.

    If you just want to make sure ptr itself is not changed, don't worry: it's passed by value (as everything in C), so even if the function changes its ptr parameter, that won't affect the pointer that was passed in.

    0 讨论(0)
提交回复
热议问题