Reputation: 211
I'm having a problem with comparing 2 char strings that are both the same:
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.
If I use:
strcpy(string, "StringToCompare");
instead of:
strncpy(string, "StringToCompare", 49);
it solves the problem, but I would rather insert the length of the string rather than it getting it itself.
What's going wrong here? How do I solve this problem?
Upvotes: 1
Views: 764
Reputation: 181
The byte count parameter in strncpy
tells the function how many bytes to copy, not the length of the character buffer.
So in your case you are asking to copy 49 bytes from your constant string into the buffer, which I don't think is your intent!
However, it doesn't explain why you are getting the anomalous result. What compiler are you using? When I run this code under VS2005 I get the correct behavior.
Note that strncpy()
has been deprecated in favor of strncpy_s
, which does want the buffer length passed to it:
strncpy_s (string,sizeof(string),"StringToCompare",49)
Upvotes: 0
Reputation: 19032
Lots of apparent guesses in the other answers, but a quick suggestion.
First of all, the code as written should work (and in fact, does work in Visual Studio 2010). The key is in the details of 'strncpy' -- it will not implicity add a null
terminating character unless the source length is less than the destination length (which it is in this case). strcpy
on the other hand does include the null
terminator in all cases, suggesting that your compiler isn't properly handling the strncpy
function.
So, if this isn't working on your compiler, you should likely initialize your temporary buffer like this:
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);
However, I suspect this is likely just an example, and in the real world your source string is 49 (again, you should pass 50 to strncpy
in this case) characters or longer, in which case the NULL terminator is NOT being copied into your temporary string.
I would echo the suggestions in the comments to use std::string
if available. It takes care of all of this for you, so you can focus on your implementation rather than these trite details.
Upvotes: 0
Reputation: 96258
strcopy
and strncpy
: in this situation they behave identically!!
So you didn't tell us the truth or the whole picture (eg: the string is at least 49 characters long)
Upvotes: -1
Reputation: 16718
You need to set the null terminator manually when using strncpy
:
strncpy(string, "StringToCompare", 48);
string[49] = 0;
Upvotes: 0
Reputation:
You forgot to put a terminating NUL character to string
, so maybe strcmp run over the end. Use this line of code:
string[49] = '\0';
to solve your problem.
Upvotes: 2