基本上,如果字符大于字符数组大小,我会使用strncpy
截断字符。
所以,我有以下变量和方法。
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
}
因此,如果我将学生姓名设置为Jackson
,它将截断为Jackso
,但是,我的colour
变量将为空,我的music
变量将为空null
。
另外,如果我试试......
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
}
我将学生姓名设为Jackson
我得到Jacksonull
之类的内容。它将null
添加到结尾
答案 0 :(得分:1)
这里(假设是Linux平台。如果您在Windows上,可能需要获取strlcpy实现,不确定。)
#include <bsd/string.h>
char studentName[6]; /* Good to know: Globals are initialized to zero */
char colour[5];
char music[7];
/* Pretty useless function since a single strlcpy call is enough */
static size_t setX(char *buf, size_t buflen, const char *new_val) {
return strlcpy(buf, new_val, buflen);
}
int main(int argc, char **argv) {
setX(studentName, 6, "Peter"); /* Please read man page and check return value */
}
现在strlcpy
保证NUL终止,只要长度参数为> 0。
答案 1 :(得分:-1)
尝试使用sizeof()
代替原始数字。它允许您在不触及代码的情况下更改数组的大小。
首先复制sizeof(array)-1
符号,然后将索引sizeof(array)-1
的最后一个符号(因为索引从0开始)设置为'\0'
。
您编辑的代码如下所示:
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, sizeof(this->studentName)-1); // Copy n-1 chars
this->studentName[sizeof(this->studentName)-1] = '\0'; // n is set to null symbol
}
void setColour (char* colour)
{
strncpy(this->colour, colour, sizeof(this->color)-1);
this->colour[sizeof(this->color)-1] = '\0';
}
void setMusic (char* music)
{
strncpy(this->music, music, sizeof(this->music)-1);
this->music[sizeof(this->music)-1] = '\0';
}