On 25 Jul 2003 03:14:55 -0700,
qa********@rediffmail.com (qazmlp) wrote:
Can anybody comment(& suggest improvements) on the following
implementation that is for
truncating the character buffer contents to the desired length?
Truncating char array
void truncateCharArray(int maxLength , char * buffer )
{
if ((0 == buffer) || !(0 < maxLength))
return;
To my eye, this is confusing. Why not simply
if (buffer == NULL || maxLength <= 0)
return;
if (maxLength < strlen(buffer))
What if maxLength is equal to the length of buffer?
{
buffer[maxLength] = '\0';
}
return;
}
Moreover, you should use size_t for the requested string length instead of
an int. Also, it would be useful to have your function return some type of
indication of success or failure.
Consider the following version of your code:
#include <string.h>
size_t truncateCharArray(size_t maxLength, char *buffer)
{
/* NULL string or illegal requested length? */
if (buffer == NULL || !maxLength)
return 0;
/* Truncate string; return length of truncated string or 0 if error */
if (maxLength <= strlen(buffer))
{
buffer[maxLength] = '\0';
return maxLength;
}
else
return 0;
}
--
Robert B. Clark (email ROT13'ed)
Visit ClarkWehyr Enterprises On-Line at
http://www.3clarks.com/ClarkWehyr/