2012-03-22 129 views
0

我遇到比较2个字符字符串都是同样的问题时:函数strncpy字符的字符串问题增加长度

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);

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

什么错吗?我该如何解决这个问题?

+2

错的是你使用的是C字符串,而不是的std :: string – 2012-03-22 19:49:06

+0

你必须添加字符串'\ 0'的结尾,因为您将“string”声明为字符的向量,而不是字符串。 – Cristy 2012-03-22 19:49:18

+1

“真实世界”中的字符串是否有49个字符长? – 2012-03-22 19:53:34

回答

2

你忘了把一个终止的NUL字符放到string,所以也许strcmp运行结束。使用此行代码:

string[49] = '\0'; 

解决您的问题。

+0

这可能是他真实的例子中的问题,但不是在他发布的测试用例中。在Linux手册页中:“如果src'的长度小于'n','strncpy()'用空字节填充'dest'的剩余部分。” – 2012-03-22 20:13:25

0

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

strncpy(string, "StringToCompare", 48); 
string[49] = 0; 
+0

只有当字符串太长。 – 2012-03-22 19:59:55

+0

@ KarolyHorvath:nem,mindig。 Én是pont ugyaneztírtam。 – 2012-03-22 20:06:26

-1

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

所以你没有告诉我们真相或整个画面(如:字符串是至少49个字符长)

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(如果有的话)。它为您处理所有这些问题,因此您可以专注于您的实施,而不是这些陈旧的细节。

0

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

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

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

注意strncpy(),取而代之的strncpy_s被弃用,这确实想传递给它的缓冲区长度:

strncpy_s (string,sizeof(string),"StringToCompare",49) 
+0

检查[strncpy](http://msdn.microsoft.com/en-us/library/xdsywd25(v = vs80).aspx)的文档...'如果count大于strSource的长度,目标字符串填充空字符直到长度count.' ...也就是说它不会复制到“StringToCompare”超出sizeof(“StringToCompare”)... +1以强调'strncpy_s' – user1055604 2012-03-23 15:46:01