5

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

非常感谢你。

4

4 回答 4

6

您可以使用const

void foo(const char * pc)

pc是指向 const char 的指针,通过使用pc您无法编辑内容。

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

所以,这取决于你,你将如何实施它。

于 2012-11-18T11:14:39.653 回答
4

是的,

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

}

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
} 

在这里学习!

于 2012-11-18T11:17:43.677 回答
3

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

除非函数接受一个const参数,否则你唯一能做的就是显式地向它传递你的数据副本,可能是使用memcpy.

于 2012-11-18T11:12:04.153 回答
0

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

什么内容?指针指向的值?在这种情况下,您可以像这样声明您的函数

void function(const int *ptr);

然后function()不能改变ptr指向的整数。

如果你只是想确保ptr自己没有被改变,别担心:它是按值传递的(就像 C 中的所有东西一样),所以即使函数改变了它的ptr参数,也不会影响传入的指针。

于 2012-11-18T11:15:36.617 回答