I have sorting function:

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];
    }
}

I ommited details about the sorting algorithm because the problem is somewhere else. Thing is, there's problem with declaration of the arrayCopy.

on lines

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

i get this error messages

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

There must be something wrong with const usage in declaration but I don't know how to fix it...

有帮助吗?

解决方案

Read const and pointer declarations from right to left:

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

So, arrayCopy is effectively an array of constant pointers (and so is array). Constant pointers cannot be moved (i.e. you cannot change where they point). Thus, you cannot overwrite them, and thus, you cannot sort them.

If you wanted an array of pointers to constant TPhone (i.e., you cannot change the fields of TPhone, but you can move pointers around), then you should move the 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

Then you can change the pointers (which are just memory addresses), but you cannot change the actual TPhone objects.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top