size_t and null characters...

Jul 7, 2010 at 9:50pm
Hello,

I just got myself a bit confused over size_t... I have written the following function to extract the last four characters of a date to get the year:

1
2
3
4
5
6
7
8
9
string yearSet(string fullDate)
{
	char yearBuf[4];
	size_t yearLength;
	
	yearLength = fullDate.copy(yearBuf,4,6);
	yearBuf[yearLength] = '\0';
	return yearBuf;
}


I assume that the code...
fullDate.copy(yearBuf,4,6)
... copies the last four char from fullDate into yearBuf....

... what does this make yearLength? Is it's value 4? Or is it the 4 characters?

Thanks for any help...
Jul 7, 2010 at 9:58pm
Jul 7, 2010 at 10:18pm

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?

Thanks.
Jul 8, 2010 at 12:02am
The function does not append a null character after the content copied.
Jul 8, 2010 at 2:13am
Why mess with char[] arrays at all?
Use the substr() member function:
http://www.cplusplus.com/reference/string/string/substr/
Jul 8, 2010 at 2:14am
ok, so it does become the 4th character... thanks for the help... I think I understand it better now..
Jul 8, 2010 at 2:42am
thanks Duoas... I think I'll try out the substr()... seems simpler...
Jul 8, 2010 at 2:34pm
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.
Last edited on Jul 8, 2010 at 2:37pm
Topic archived. No new replies allowed.