在函数中传递的指针的内存位置将被删除
Memory location for a pointer passed in a function gets deleted
问题:我似乎无法将指针设置为在函数内部创建的地址。它总是被设置为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;
}
您似乎希望对list
的更改在函数返回后有效:由于list
是通过值传递的,因此函数内部操作的对象恰好是您传递的对象的副本。您可能希望通过引用传递对象,即:
void listAdd(int*& list, int &length) {
// ...
}
或返回结果
int* listAdd(int* list, int& length) {
// ...
return list;
}
list = listAdd(list, length);
实际上,您确实希望将对象封装在一个类中,或者只使用std::vector<int>
。
相关文章:
- C++ 从具有开始位置和结束位置的列表中删除
- 在双链表中的某个位置删除
- C++访问冲突读取位置0xDDDDDDCD当我尝试删除已更新的数组时
- 如何正确删除一行控件并在该位置动态创建一个新控件
- C++放置位置删除如何在内部(C++运行时)工作?如何克服其局限性?
- 从文件对象的当前位置删除字符
- 设置位置时QT删除对象()
- 我如何在代码中找到(和删除)需要管理员特权的位置
- 试图从链接列表中删除位置
- 指向对象的内存位置的指针已在程序中删除,但仍提供正确答案而不是垃圾值
- 在任意位置进行快速查找和删除的Deque样数据结构
- 应删除传递参数时创建对象的位置
- 如何在不删除任何字符的情况下将字符从字符串中的某个位置移动到其最前面
- 删除位置 (C++)
- C 删除具有内存位置的操作员
- 我可以使用C++删除堆栈中的特定位置数据吗?
- 不受限制的工会上的位置删除
- 如何根据列表中的位置删除特定项目
- 在列表末尾插入一个整数,并在第n个位置删除
- 为什么c++中没有位置删除表达式