[英]How to clear dynamic array in C++ and how much is on the stack?
I have a struct in my C++ program. 我的C ++程序中有一个结构。 At the end of my function I do a delete [] to free the allocated memory. 在函数结束时,我执行delete []释放分配的内存。 How do I erase all elements in code without doing a for() loop? 如何在不进行for()循环的情况下擦除代码中的所有元素?
struct sServerStatus
{
TCHAR sServer[MAX_COMPUTERNAME_LENGTH+1]; // The NetBIOS name of the computer + 1 null terminating character.
};
sServerStatus *sServersType1 = new sServerStatus[1024];
Q1. Q1。 How do I clear the array after I fill some of the items up? 填满一些项目后如何清除阵列? Do I use SecureZeroMemory? 我是否使用SecureZeroMemory?
SecureZeroMemory(sServersType1 , sizeof(sServersType1 ));
Q2. Q2。 What is on the stack? 堆栈上有什么? I assume the allocated space on the stack is just MAX_COMPUTERNAME_LENGTH+1 and the 1024 elements are on the heap? 我假设堆栈上分配的空间仅为MAX_COMPUTERNAME_LENGTH + 1,堆上有1024个元素?
new sServerStatus[1024];
will allocate 1024 sServerStatus
instances on the heap . 将在堆上分配1024个sServerStatus
实例。
Each one of those has MAX_COMPUTERNAME_LENGTH+1
TCHAR
s. 其中每个都有MAX_COMPUTERNAME_LENGTH+1
TCHAR
。 (Also on the heap since that's where the objects are allocated.) (也位于堆上,因为这是分配对象的位置。)
The only thing on the stack is the pointer sServersType1
. 堆栈上唯一的东西是指针 sServersType1
。
To clean everything up, note that you didn't use new
to allocate (2) so you don't need to use delete
either. 要清理所有内容,请注意,您没有使用new
来分配(2),因此也不需要使用delete
。 That memory will be freed once an sServerStatus
instance is destructed. 销毁sServerStatus
实例后,将释放该内存。
But you will need to free the memory you allocated using new
. 但是您将需要释放使用new
分配的内存。 Do do this you need to write delete[] sServersType1
. 为此,您需要编写delete[] sServersType1
。 Note carefully the []
. 仔细注意[]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.