2012-11-18 61 views

回答

3

我必须确保除非功能需要一个const参数函数不修改内容

,你唯一可以做的事被明确传递您的数据的副本,也许使用memcpy创建。

+1

即使你使用(const int的* PTR)作为参数,你仍然可以改变值所指向(通过创建函数内的第二指针,例如)。 100%确定它不会改变的唯一方法就是传递一个值的副本。对? –

+2

@DanielS如果它创建一个非const指针并使其指向const指针的内容,它将进入未定义的行为区域。即它是无效的代码。 – cnicutar

+0

我不能使用const,我只是想确保函数使用通过指针传递的内容的副本。 memcpy看起来是最好的解决方案,请问你能告诉我语法吗? – Mc128k

6

您可以使用const

void foo(const char * pc)

这里pc是指针为const char和使用pc您不能编辑内容。

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

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

0

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

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

void function(const int *ptr); 

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

如果你只是想确保ptr本身没有改变,不要担心:它是按值传递的(因为C中的所有东西),所以即使函数改变了它的参数ptr,也不会影响指针中传递。

+1

即使您声明了您所做的功能,仍然可以更改ptr指向的值。我们可以在函数内部创建第二个指针,例如,在ptr上赋予它的内存地址,然后在那里更改值。 –

+0

@DanielS好吧,如果你有'void func(const int * ptr)'函数,那么编写'*(int *)ptr = 42;'是未定义的行为,所以你错了。 – 2012-11-18 11:52:43

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 
} 

Learn here!

+0

“在void函数(const int * ptr)中,ptr是常量,但它的指针不是常量,因此void函数中的ptr = 10(const int * ptr)是一个有效的表达式。我不认为这是正确的。 * ptr只在这种情况下被读取,所以你不能归因于它。 –

+0

@丹尼尔斯:是的,你是对的 –

+0

@丹尼尔斯:谢谢,我编辑了我的答案。 –