1

I am confuse in GetAT and aryString[n], as follow code

CArray <CString, CString> arySctring;
aryString.SetSize(3);

aryString.Add(_T("a1"));
aryString.Add(_T("a222"));
aryString.Add(_T("a3"));

TRACE(_T("%d %s"), aryString.GetCount(), aryString[0]);

the TRACE result is "6 ", it means aryString[0] is no data, I instead of aryString.GetAt(0), the result is same.

Why?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
user1753112
  • 203
  • 2
  • 17

3 Answers3

3

.SetSize(3);
reserve 3 "rooms". Calling
Add();
three times, reserve another 3 "rooms", hence you get 6 at count and your array is as follow:
  1. ""
  2. ""
  3. ""
  4. "a1"
  5. "a222"
  6. "a3"
. To get the result I guess you want, once you've set size, you can do:
aryString.SetSize( 3 );
aryString[0] = "a1";
aryString[1] = "a222";
aryString[2] = "a3";

As side note, MFC provides you with CStringArray class, so you haven't to do:

CArray<CString,CString>
IssamTP
  • 2,408
  • 1
  • 25
  • 48
1

when you do aryString.SetSize(3); aryString reserves 3 items with empty string. when you Add three new strings at the end , the item count of the array is 6. the first item is empty string, aryString.GetAt[3] will return a1, function add will auto increase the size of the array ,you do not have to SetSize(3) to reserve space

user1793036
  • 199
  • 1
  • 8
michaeltang
  • 2,850
  • 15
  • 18
0

I use as follow code to asign the element

aryString.SetAtGrow(0, _T("a"));
aryString.SetAtGrow(1, _T("a"));
user1753112
  • 203
  • 2
  • 17