I converted the following code containing std::wstring to wchar_t (next code block) and I am getting memory dump errors:
Below is code with std::wstring:
std::wstring RemoveFirstAndLast(std::wstring str)
{
std::wstring removeFirst = L"";
bool first = true;
for (std::wstring::iterator it = str.begin(); it != str.end(); ++it)
{
const wchar_t *brckt = L"[";
const wchar_t *empty = L" ";
const wchar_t *curlyBrkt = L"{";
if (((*it) == (*curlyBrkt)) && (first))
{
first = false;
removeFirst = removeFirst + (*it);
}
else
{
removeFirst = removeFirst + (*it);
}
}
std::wstring removeLast = L"";
bool last = true;
for (std::wstring::reverse_iterator it = removeFirst.rbegin(); it != removeFirst.rend(); ++it)
{
const wchar_t *brckt = L"]";
const wchar_t *empty = L" ";
const wchar_t *curlyBrkt = L"}";
if (((*it) == (*curlyBrkt)) && (last))
{
last = false;
removeLast = (*it) + removeLast;
}
else
{
removeLast = (*it) + removeLast;
}
}
return removeLast;
}
Below is the same code as above but with wchar_t*:
wchar_t* RemoveFirstAndLast(wchar_t *str)
{
wchar_t *removeFirst = L"";
int length = wcslen(str);
bool first = true;
for (int i = 0; i < length; i++)
{
const wchar_t *brckt = L"[";
const wchar_t *empty = L" ";
const wchar_t *curlyBrkt = L"{";
if (((str[i]) == (*curlyBrkt)) && (first))
{
first = false;
wcsncat_s(removeFirst, (wcslen(removeFirst) + 1) * 2, &str[i], 1); //removeFirst = removeFirst + (str[i]);
}
else
{
wcsncat_s(removeFirst, (wcslen(removeFirst) + 1) * 2, &str[i], 1); //removeFirst = removeFirst + (str[i]);
}
}
wchar_t *removeLast = L"";
length = wcslen(removeFirst);
bool last = true;
for (int i = length; i >= 0; i--)
{
const wchar_t *brckt = L"]";
const wchar_t *empty = L" ";
const wchar_t *curlyBrkt = L"}";
if (((removeFirst[i]) == (*curlyBrkt)) && (last))
{
last = false;
wchar_t *temp2 = (wchar_t*)calloc((wcslen(removeLast) * 2) + 1, sizeof(wchar_t));
wcsncat_s(temp2, (wcslen(temp2)) * 2, &removeFirst[i], 1);
wcsncat_s(temp2, (wcslen(temp2)) * 2, removeLast, wcslen(removeLast));
removeLast = temp2;
}
else
{
wchar_t *temp3 = (wchar_t*)calloc((wcslen(removeLast) * 2) + 1, sizeof(wchar_t));
wcsncat_s(temp3, (wcslen(temp3)) * 2, &removeFirst[i], 1);
wcsncat_s(temp3, (wcslen(temp3)) * 2, removeLast, wcslen(removeLast));
removeLast = temp3;
//removeLast = (removeFirst[i]) + removeLast;
}
}
return removeLast;
}
The code is trying to remove first and last characters. As a beginner I was trying to understand why I am getting errors while simply converting the code from std::wstring to wchar_t*? The error creates a memory dump? Can someone please help me understand as to where am I making mistake?
Aucun commentaire:
Enregistrer un commentaire