2016-10-13 32 views
0

我剛開始學習如何使用C語言的指針,我跨過了他們在我使用這本書有這個特殊的代碼示例:這個指針示例不會產生錯誤?

#include <stdio.h> 
#define SIZE 10 

void bubbleSort(int * const array, const size_t size); // prototype 

int main(void) 
{ 
// initialize array a 
    int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 

    size_t i; // counter 

    puts("Data items in original order"); 

    // loop through array a 
    for (i = 0; i < SIZE; ++i) 
    { 
     printf("%4d", a[ i ]); 
    } // end for 

    bubbleSort(a, SIZE); // sort the array 

    puts("\nData items in ascending order"); 

    // loop through array a 
    for (i = 0; i < SIZE; ++i) 
    { 
     printf("%4d", a[ i ]); 
    } // end for 

    puts(""); 

return 0; 
} 

// sort an array of integers using bubble sort algorithm 
void bubbleSort(int * const array, const size_t size) 
{ 

    void swap(int *element1Ptr, int *element2Ptr); // prototype 
    unsigned int pass; // pass counter 
    size_t j; // comparison counter 

    // loop to control passes 
    for (pass = 0; pass < size - 1; ++pass) 
    { 

     // loop to control comparisons during each pass 
     for (j = 0; j < size - 1; ++j) 
     { 

      // swap adjacent elements if they’re out of order 
      if (array[ j ] > array[ j + 1 ]) 
      { 
       swap(&array[ j ], &array[ j + 1 ]); 
      } // end if 
     } // end inner for 
    } // end outer for 
} // end function bubbleSort 

// swap values at memory locations to which element1Ptr and 
// element2Ptr point 
void swap(int *element1Ptr, int *element2Ptr) 
{ 
    int hold = *element1Ptr; 
    *element1Ptr = *element2Ptr; 
    *element2Ptr = hold; 
} // end function swap 

什麼我不理解就是爲什麼這沒有給出任何錯誤,因爲我看到在bubbleSort函數的參數中,數組前有一個const,使得它的數組指向const,因此它不能被更改。但是在這個函數中,我們正在交換數組中的元素,所以不應該由於數組發生更改而產生錯誤?我假設我可能並不完全瞭解指針如何在這種情況下工作?

+0

'const array'意味着'array'是'const',而不是它指向的東西。 'array'對於指針來說是個不好的名字,我建議改變它! –

+0

@ M.M抱歉,我只是簡單地輸入 – dj2k

回答

2

int * const array的含義是指針本身不能修改,但可以修改數組的值。換句話說,假設我們在內存中有一個塊,並將地址保存到另一塊內存中。在const之後的情況下,該塊保存地址的值不能更改,但可以更改具有實際數組值的另一個存儲塊。所以你不能實例化一部分新內存,並把它的地址放入array

+0

這本書中的示例中顯示的內容哦,現在我覺得很傻。在閱讀你的解釋之後,我意識到說'int * const數組'和'const int *數組'有區別。在我的書中還有另外一個例子,它打算爲讀取const char * sPtr的常量數據創建一個非常量指針,出於某種原因,我認爲這與我的問題中的例子類似。 – dj2k

+0

@ dj2k這是一個誠實的錯誤 – afsafzal

相關問題