c++ - Access violation writing location with dynamic array -


i have member variable points wchar_t array hold input given user through console.

wchar_t ** marray; 

then, in member function, ask input user , store in std::wstring. afterwards, use length of wstring dynamically allocate memory marray, , assign each character in loop. however, "access violation writing location" error.

std::wstring givenwstring; std::cin.ignore(); std::getline(std::wcin, givenwstring); marray = new wchar_t*[givenwstring.length()]; (size_t = 0; < givenwstring.length(); i++) {     *marray[i] = givenwstring.at(i); } 

i don't know why getting access violation error because assigning each character wstring each index in dynamic array.

you must store data in dynamic array of appropriate objects, wchar_t in case. i.e. need pointer wchar_t manage array.

std::unique_ptr<wchar_t[]> marray;   // unique_ptr takes care of delete[] std::wstring givenwstring; std::cin.ignore(); std::getline(std::wcin, givenwstring); marray.reset(new wchar_t[givenwstring.length()+1]); for(size_t = 0; < givenwstring.length(); i++)     marray[i] = givenwstring.at(i); marray[givenwstring.length()] = 0; 

however, there no conceivable reason such construction. far best way keep array of wchar_t std::wstring. moveover, whenever need representation raw const wchar_t* (c-style string), can use std::string::c_str(), example

void old_code(const wchar_t*);     // old api old_code(marray.c_str()); 

finally, should explain why access violation.

wchar_t**marray = new wchar_t*[givenwstring.length()]; 

allocates array of wchar_t* not initialised (and hence contain random data). *marray returns first of these randomly initialised pointers, when *marray[0]=... attempts write memory @ random address.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -