I need to implement a method that concatenates different characters into a char* without using any standard library (it’s part of the specifications). So, no strcat or strcopy. I can’t use strings neither.
Here’s what I tried to do (the chars are stored in a StringList I implemented myself, hence the “GetCell” method and the ->next pointer) :
char* IntlFinder::ConcatenateSrc ( int nSource, long beginPosition )
char* res = new char;
Cell* cell = ComList.GetCell(beginPosition);
for (long i = beginPosition; i <= (CountTab[nSource]); i++)
{
if (nSource == 0 || cell->elem.source == nSource)
{
res[i-beginPosition] = cell->elem.caractere;
}
cell = cell->next;
}
*res = '\0';
return res;
}
When I’m debugging, this looks great until I get to a certain char, and then it bugs for no reason (the cell it’s pointing to at that moment looks normal, with a valid adress).
Any thoughts on that?
—
EDIT: I tried to do this instead:
for (long i = beginPosition; i <= (CountTab[nSource]-1); i++)
{
if (nSource == 0 || cell->elem.source == nSource)
{
*res = cell->elem.caractere;
++res = new char;
}
cell = cell->next;
}
Which is supposed to increment the pointer and allocate memory (so I can add another value at the next iteration), and I don’t have any SIGSERV error anymore.
But when I return this pointer or the original value of the pointer, poiting to the first char, I get nothing (in the first case) or just the first character (in the second case).
I didn’t forget to add ‘\0’ at the end, but this still doesn’t make it a string.
Something like:
Provided that
destis big enough to carry both itselt andsrc. Otherwise, this may cause unexpected results because of writing outside the bounds of array.ADD