strncpy不能正确存储字符C.

时间:2014-12-02 22:26:28

标签: c arrays char truncate strncpy

基本上,如果字符大于字符数组大小,我会使用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添加到结尾

2 个答案:

答案 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'; 
}