简体   繁体   中英

comparing static char [] and const char *

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM