1

我在比较两个相同的 char 字符串时遇到问题:

char string[50];

strncpy(string, "StringToCompare", 49);

if( !strcmp("StringToCompare", string) )
//do stuff
else
//the code runs into here even tho both strings are the same...this is what the problem is.

如果我使用:

strcpy(string, "StringToCompare");

代替:

strncpy(string, "StringToCompare", 49);

它解决了这个问题,但我宁愿插入字符串的长度而不是它本身。

这里出了什么问题?我该如何解决这个问题?

4

5 回答 5

2

您忘记将终止 NUL 字符放入string,所以 strcmp 可能会跑到最后。使用这行代码:

string[49] = '\0';

来解决你的问题。

于 2012-03-22T19:49:04.197 回答
0

使用时需要手动设置空终止符strncpy

strncpy(string, "StringToCompare", 48);
string[49] = 0;
于 2012-03-22T19:49:08.980 回答
0

其他答案中有很多明显的猜测,但是一个快速的建议。

首先,编写的代码应该可以工作(事实上,在 Visual Studio 2010 中确实可以工作)。关键在于“strncpy”null的细节——除非源长度小于目标长度(在这种情况下),否则 它不会隐式添加终止字符。strcpy另一方面,null在所有情况下都包含终止符,这表明您的编译器没有正确处理该strncpy函数。

所以,如果这在你的编译器上不起作用,你应该像这样初始化你的临时缓冲区:

char string[50] = {0}; // initializes all the characters to 0

// below should be 50, as that is the number of 
// characters available in the string (not 49).
strncpy(string, "StringToCompare", 50);

但是,我怀疑这可能只是一个示例,在现实世界中,您的源字符串是 49 个(同样,在这种情况下您应该传递 50 个strncpy)字符或更长,在这种情况下,NULL 终止符不会被复制到您的临时细绳。

如果有的话,我会回应评论中的建议std::string。它会为您处理所有这些,因此您可以专注于您的实现,而不是这些陈腐的细节。

于 2012-03-22T19:59:10.633 回答
0

中的字节计数参数strncpy告诉函数要复制多少字节,而不是字符缓冲区的长度。

因此,在您的情况下,您要求将常量字符串中的 49 个字节复制到缓冲区中,我认为这不是您的意图!

但是,它不能解释为什么您会得到异常结果。你用的是什么编译器?当我在 VS2005 下运行此代码时,我得到了正确的行为。

请注意,strncpy()已弃用strncpy_s,它确实希望将缓冲区长度传递给它:

strncpy_s (string,sizeof(string),"StringToCompare",49)
于 2012-03-22T19:59:19.790 回答
-1

strcopystrncpy:在这种情况下,它们的行为相同!

所以你没有告诉我们真相或全貌(例如:字符串至少有 49 个字符长)

于 2012-03-22T19:49:39.127 回答