简体   繁体   中英

Dereference structure array items in C++

I have a problem with dereferencing my array objects with the following code. What I would like to do is to copy the array elements of *pstructDocuments into a global vector. I know global variables are not the best way, but for testing purposes I would like to fill the global vector with the structure elements.

struct DOCUMENTS{
    wchar_t* TYPE;
    wchar_t* PATH;
}

std::vector<DOCUMENTS> CdeskDocumentsVec

void initDocuments(DOCUMENTS *pstructDocuments, int size){

  for (int i = 0; i < size; i++)
  {
     DOCUMENTS test1 = {};
     test1.PATH = pstructDocuments[i].PATH;
     test1.TYPE = pstructDocuments[i].TYPE;
     CdeskDocumentsVec.push_back(test1);
  }
}

I have been tested some copy functions but they did not work as expected. So I hope that someone can help me to find the solution for creating a global copy with all array elements.....

This

DOCUMENTS test1 = {};
test1.PATH = L"PATH_TEXT";
test1.TYPE = L"TYPE_TEXT";
CdeskDocumentsVec.push_back(test1);

works with defined and given Strings.

This

CdeskDocumentsVec.push_back(pstructDocuments[i]);

does not work. I think this has to do with the pointers...

Not working means I am not able to iterate through the vector and get access to the strings that are stored in the DOCUMENT structure in the pstructDocuments array...

UPDATE: When I copy the data

const size_t len = wcslen(pstructDocuments[i].PATH);
test1.PATH = new wchar_t[len + 1];
wcsncpy(test1.PATH, pstructDocuments[i].PATH, len + 1);

it seems to work....

Make a copy of the strings from the pstructDocuments[i] instead of assigning them. When you assign them you are storing the pointer to the original strings rather than to copies. If the original strings are destroyed you have a problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM