views:

49

answers:

2
static char a[255] = "\0";
and
const char *b = " ";

now when I assign "abc" to a and b, for a the remainig 252 bytes stay '\0' and for b its not like that. So, when I try to compare them, they come out to be different. One solution is to just compare till sizeof(b) as we do in strncmp(). Is there any other way of doing it? Probably by converting one to another?

Thanks in advance.

A: 

Well, firstly you don't want to assign "abc" to b. It will cause a memory leak with C-style strings when you change the value.

To compare you want to use the strcmp function. It's in the library.

OmnipotentEntity
+4  A: 

That's because b does not have a "remaining 252 bytes". b is created as a pointer to memory which contains the two characters <space> and <nul> and nothing else.

When you assign to b, you actually change the pointer to point at the four characters a, b, c and <nul>, but there's still nothing after there that you can safely use.

strcmp is the accepted way to compare strings in C, notwithstanding those namby-pamby strncmp-loving types that tell you it's unsafe*a, but they have no right coding in C in the first place :-)


*a It is unsafe if your strings may not be null-terminated. But then again, if they're not null-terminated, they're not technically strings. For processing strings, strcmp is the right tool for the job.

paxdiablo
+1 for the "if they're not null-terminated, they're not technically strings".
John Bode