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
Try using
sizeof()instead of raw numbers. It allows you to change array's sizes without touching your code.You first copy
sizeof(array)-1symbols and then set the last symbol which is of indexsizeof(array)-1(because indexing starts from 0) to'\0'.Your code edited would look like this: