请教CStringArray的GetSize函数问题
白虹李李 2010-12-26 10:08:08 按照MSDN里讲的,使用CStringArray最好先调用SetSize函数进行初始化:
Note Before using an array, use SetSize to establish its size and allocate memory for it. If you do not use SetSize, adding elements to your array causes it to be frequently reallocated and copied. Frequent reallocation and copying are inefficient and can fragment memory.
可是调用了这个函数后GetSize的结果就不正确了。代码:
CString a1;
a1="abc";
CStringArray strArray;
//strArray.SetSize(50);
int index=strArray.Add(a1);
int count=strArray.GetSize();
如果没有strArray.SetSize(50);这句,那么执行下来index=0,count=1。
如果把注释去掉,执行下来index=32,count=33(可能各个机器根据情况不同?)
这个问题我是在另一段代码中发现的,当时也是类似的代码,执行下来插入第一个元素后index=1而不是我预期的0.然后调用GetSize为2,这样我循环处理就出问题了。
所以写了这段代码来做实验。
请教一下高手,这个是为什么啊?