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.
<
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!