Basically, I use strncpy
to truncate the characters if it is greater than the character array size.
So, I have the following variables and methods.
char studentName[6];
char colour[5];
char music[7];
strcpy(this->studentName, "null");
strcpy(this->colour, "null");
strcpy(this->music, "null"):
void setName (char* studentName)
{
strncpy(this->studentName, studentName, 6);
this->studentName[6] = '\0'; // SET LAST TO NULL POINTER
}
void setColour (char* colour)
{
strncpy(this->colour, colour, 5);
this->colour[5] = '\0'; // SET LAST TO NULL POINTER
}
void setMusic (char* music)
{
strncpy(this->music, music, 7);
this->music[7] = '\0'; // SET LAST TO NULL POINTER
}
So, if I set the student name to Jackson
, it will truncate to Jackso
, however, my colour
variable will be blank and my music
variable will be null
.
Also, if I try...
void setName (char* studentName)
{
strncpy(this->studentName, studentName, 6);
this->studentName[6-1] = '\0'; // SET LAST TO NULL POINTER
}
void setColour (char* colour)
{
strncpy(this->colour, colour, 5);
this->colour[5-1] = '\0'; // SET LAST TO NULL POINTER
}
void setMusic (char* music)
{
strncpy(this->music, music, 7);
this->music[7-1] = '\0'; // SET LAST TO NULL POINTER
}
and I set the student name to Jackson
I get something like Jacksonull
. It adds null
to the end
Here (assumes Linux platform. You might have to fetch strlcpy implementation if your on Windows, not sure.)
Now
strlcpy
guarantees NUL termination as long as length argument is >0.