Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Thank you very much.

like image 346
John White Avatar asked Nov 18 '12 11:11

John White


People also ask

How do you pass a pointer to a function in C?

C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer type.

How would you define a pointer in a read only mode?

A pointer is a reference to data, so the only way to do so is to copy the data, there's nothing like a read-only memory permission (unless it's the part holding the executable itself).

How do we pass a pointer to a function?

Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.

Can you pass a pointer to a function that takes a reference?

Passing By Pointer Vs Passing By Reference in C++ In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result.


2 Answers

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.

like image 68
Omkant Avatar answered Nov 15 '22 03:11

Omkant


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!

like image 21
Grijesh Chauhan Avatar answered Nov 15 '22 03:11

Grijesh Chauhan