在 C++ 中使用 new 运算符时,我不能将指针更改为另一个指针吗?
Can't I change the pointer to another one when I use new operator in C++?
我在学习C++的动态分配时,有不懂的地方问你
当St指针指向动态分配的内存时,如果将存储在St中的地址移动到另一个指针“ptr”,是否可以删除“St”并使用“ptr”代替?
如果我删除“St”动态分配,是否可以将地址移动到另一个指针并立即删除“St”,因为分配的space并没有消失,而是断开了指针“St”与space?
下面是我写的代码。
学生是一个结构。
int main()
{
case 1:
{
Student* ptr = NULL;
Student* St = new Student[10];
ptr = St;
delete[] St;
St = NULL;
break;
}
case 2:`enter code here`
{
printdata(ptr);break;
}
}
在您从 new Student[10]
返回的指针上调用 delete[]
后,该指针的值为 不确定。 St
和 ptr
都是这样,但你重新分配 St
。 (自 C++11 起,使用 nullptr
而不是 NULL
。)
在 delete[]
之后取消引用从 new Student[10]
返回的指针的行为是 未定义。
您不能使用刚刚释放的内存。该地址的内存可能仍然可用(事件直到程序关闭),但不能保证并且程序可能会将其用于其他用途。
Can I delete "St" and use "ptr" instead if I move the address stored
in St to another pointer "ptr" when the dynamically allocated memory
is pointed by the St pointer?
如果 St 指向你的数组,你也可以让 ptr 指向它,但这不是一个转移。您实际传输的是您指向的对象的地址。 2个指针将指向同一个对象。
如果你用delete[]删除对象(你删除的是对象,而不是指针),那么2个指针将不指向任何东西。所以你在这里真正想做的是让 ptr 指向同一个对象,然后让 St 指向 null。
Student* ptr = NULL;
Student* St = new Student[10];
ptr = St;
St = NULL;
编辑:如果可以帮助您理解,这里是您可以显示的...
int x = 4;
int* p = &x;
cout << "x = " << x << " value of x." << endl;
cout << "&x = " << &x << " adress of x." << endl;
cout << "*p = " << *p << " the value of what p points to." << endl;
cout << "p = " << p << " the actual value of p which is the adress of x." << endl;
我在学习C++的动态分配时,有不懂的地方问你
当St指针指向动态分配的内存时,如果将存储在St中的地址移动到另一个指针“ptr”,是否可以删除“St”并使用“ptr”代替?
如果我删除“St”动态分配,是否可以将地址移动到另一个指针并立即删除“St”,因为分配的space并没有消失,而是断开了指针“St”与space?
下面是我写的代码。 学生是一个结构。
int main()
{
case 1:
{
Student* ptr = NULL;
Student* St = new Student[10];
ptr = St;
delete[] St;
St = NULL;
break;
}
case 2:`enter code here`
{
printdata(ptr);break;
}
}
在您从 new Student[10]
返回的指针上调用 delete[]
后,该指针的值为 不确定。 St
和 ptr
都是这样,但你重新分配 St
。 (自 C++11 起,使用 nullptr
而不是 NULL
。)
在 delete[]
之后取消引用从 new Student[10]
返回的指针的行为是 未定义。
您不能使用刚刚释放的内存。该地址的内存可能仍然可用(事件直到程序关闭),但不能保证并且程序可能会将其用于其他用途。
Can I delete "St" and use "ptr" instead if I move the address stored in St to another pointer "ptr" when the dynamically allocated memory is pointed by the St pointer?
如果 St 指向你的数组,你也可以让 ptr 指向它,但这不是一个转移。您实际传输的是您指向的对象的地址。 2个指针将指向同一个对象。
如果你用delete[]删除对象(你删除的是对象,而不是指针),那么2个指针将不指向任何东西。所以你在这里真正想做的是让 ptr 指向同一个对象,然后让 St 指向 null。
Student* ptr = NULL;
Student* St = new Student[10];
ptr = St;
St = NULL;
编辑:如果可以帮助您理解,这里是您可以显示的...
int x = 4;
int* p = &x;
cout << "x = " << x << " value of x." << endl;
cout << "&x = " << &x << " adress of x." << endl;
cout << "*p = " << *p << " the value of what p points to." << endl;
cout << "p = " << p << " the actual value of p which is the adress of x." << endl;