ok... so fullDate.copy will give four characters and the yearLength will be assigned to the number of characters? Does this mean the null character is assigned to the 4th element in yearBuf?
Does this mean the null character is assigned to the 4th element in yearBuf?
[...]
ok, so it does become the 4th character... thanks for the help... I think I understand it better now..
No, no. I think everybody has skipped your question. Although std::string is a much better solution, I'll point out a flaw and answer your question.
1 2 3 4 5 6 7 8 9 10 11
string yearSet(string fullDate)
{
char yearBuf[4]; // allocate 4 characters (indexes 0-3)
size_t yearLength;
yearLength = fullDate.copy(yearBuf,4,6); // copy 4 characters into yearBuf
// and set yearLength to 4
yearBuf[yearLength] = '\0'; // write a null to the 5th character--beyond the end of
// yearBuf because array indexes start at 0
return yearBuf;
}
To fix the buffer overrun, you would want to allocate 5 characters: 4 for the year and 1 for the null.