[英]C++ Sorting array of const pointers to structs
我有排序功能:
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
使用一定存在问题,但我不知道如何解决...
从右到左读取const和指针声明:
TPhone * const * arrayCopy
^ ^ ^ ^ ^
| | | | \---- arrayCopy is a
| | | \------------ pointer to
| | \------------------- const
| \-------------------------- pointer to
\--------------------------------- TPhone
因此,arrayCopy实际上是一个常量指针数组(array也是如此)。 恒指针不能移动(即你不能改变它们所指向的位置 )。 因此,您无法覆盖它们,因此也无法对其进行排序。
如果您想要一个指向常量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对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.