0

私はソート機能を持っています:

void countingSort(TPhone * const * array, int count) {

    // some code

    // making copy od array
    TPhone * const * arrayCopy = new TPhone * [count];

    for(int i = 0; i < count; i++) {
        arrayCopy[i] = array[i];
    }

    for(int i = 0; i < count; i++) {
        int index = // some function to determine where to place array[i]
        array[index] = arrayCopy[i];
    }
}

問題は別の場所にあるため、並べ替えアルゴリズムの詳細は省略しました。問題は、 の宣言に問題がありarrayCopyます。

オンライン

arrayCopy[i] = array[i]
...
array[index] = arrayCopy[i];

このエラーメッセージが表示されます

error: assignment of read-only location ‘*(arrayCopy + ((sizetype)(((long unsigned int)i) * 8ul)))’
error: assignment of read-only location ‘*(array + ((sizetype)(((long unsigned int)index) * 8ul)))’

宣言の使用法に問題があるに違いありませんがconst、修正方法がわかりません...

4

1 に答える 1

3

const とポインターの宣言を右から左に読みます。

TPhone * const * arrayCopy
   ^   ^   ^   ^    ^
   |   |   |   |    \---- arrayCopy is a 
   |   |   |   \------------ pointer to
   |   |   \------------------- const
   |   \-------------------------- pointer to
   \--------------------------------- TPhone

したがって、arrayCopy は事実上、定数ポインターの配列です (配列もそうです)。定数ポインターは移動できません (つまり、ポインターが指す場所を変更することはできません)。したがって、それらを上書きすることはできず、したがってそれらをソートすることはできません。

定数 TPhone へのポインターの配列が必要な場合 (つまり、TPhone のフィールドを変更することはできませんが、ポインターを移動することはできます)、const を移動する必要があります。

pointer to constant TPhone:
TPhone const *   // right-to-left

array of pointer to constant TPhone:
TPhone const * []   // right-to-left
but since arrays can't easily be passed to functions, you can use a pointer:
TPhone const * *   // right-to-left

その後、ポインタ(単なるメモリ アドレス) を変更できますが、実際の TPhone オブジェクトを変更することはできません。

于 2013-10-30T22:46:42.437 に答える