我找到了一个调整数组大小的函数,但是我很难理解它是如何工作的(或者它是否正常工作)。为了测试,我将“temp”数组设置为新值,并将“startCounter”分配给该值,但startCounter的内存位置不会更改。这是我的代码:
int * startCounter;
void resizeArray(int *&arraySent,int origSize,int newSize) {
output << "&arraySent " << &arraySent << endl;
output << "arraySent[0] " << arraySent[0] << endl;
int* temp = new int[newSize];
output << "&temp " << &temp << endl;
for (int i=0; i<origSize; i++) {
temp[i] = arraySent[i];
}
temp[0]=744;
delete [] arraySent;
arraySent = temp;
output << "&arraySent " << &arraySent << endl;
}
//....
startCounter = new int [3];
startCounter[0]=345;
output << &startCounter << endl;
resizeArray(startCounter,3,10);
output << "startCounter[0]" << startCounter[0] << endl;
output << "&startCounter" << &startCounter << endl;
以下是我从中获得的输出:
&startCounter 0x60fab8
&arraySent 0x60fab8
arraySent[0] 345
&temp 0x82cfe54
&arraySent 0x60fab8
startCounter[0] 744
&startCounter 0x60fab8
我的问题是,为什么在删除它并将其分配给新的“temp”数组后,startCounter的内存位置不会从0x60fab8改变?它现在不应该变成0x82cfe54吗?
P.S。我理解向量等,但主要是关于理解这个特定函数是如何工作的。
答案 0 :(得分:2)
void resizeArray(int *&arraySent,int origSize,int newSize) {
output << "&arraySent " << &arraySent << endl;
输出指针变量的地址,而不是它所持有的地址。
简单地省略地址运算符以获得(可能)预期的效果
答案 1 :(得分:1)
&startCounter
是指针的地址,而不是它指向的地址。它的价值不会改变。只需使用startCounter
。