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

后端 未结 4 376
北海茫月
北海茫月 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 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.

提交回复
热议问题