问题:我似乎无法设置指向函数内部创建的地址的指针。它总是设置为Null,我该如何解决这个问题?
问题:我认为问题是由另一个函数内部创建的变量引起的。发生的事情是在函数执行后,指针再次设置为NULL。
的代码:
void listAdd(int *list, int &length) {
int* tempList = new int[ length + 1 ];
for( int i = 0; i < length; i ++ )
{
(tempList)[ i ] = (list)[ i ];
}
cout << " Previous adress: " << hex << list << endl;
if ( list != NULL )
delete[] list;
list = new int[ length + 1 ];
cout << " New address: " << hex << list << endl << dec;
for( int i = 0; i < length; i ++ )
{
(list)[ i ] = (tempList)[ i ];
}
delete[] tempList;
cout << " Enter a number: ";
int stored = 0;
cin >> stored;
(list)[length -1] = stored;
length ++;
cout << " Length: " << length << "\n";
cout << " value at array point 0: " << (list)[length -1];
cout << "\n retry " << (list)[length-1] <<"\n";
cout << "\n \n \n This is pointing to 0x" << hex << list << '\n' << flush;
}
答案 0 :(得分:1)
在函数返回后,您似乎希望对list
的更改有效:由于list
是按值传递的,因此在函数内部操作的对象恰好是您的副本传入。您可能要么通过引用传递对象,即:
void listAdd(int*& list, int &length) {
// ...
}
...或返回结果
int* listAdd(int* list, int& length) {
// ...
return list;
}
list = listAdd(list, length);
嗯,实际上,你真的想要将对象封装在一个类中,或者只是使用std::vector<int>
。