2012-11-18 64 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

@丹尼爾斯:謝謝,我編輯了我的答案。 –