Compare equality of char[] in C

别等时光非礼了梦想. 提交于 2020-01-10 03:45:08

问题


I have two variables:

char charTime[] = "TIME";
char buf[] = "SOMETHINGELSE";

I want to check if these two are equal... using charTime == buf doesn't work.

What should I use, and can someone explain why using == doesn't work?

Would this action be different in C and C++?


回答1:


char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE";

C++ and C (remove std:: for C):

bool equal = (std::strcmp(charTime, buf) == 0);

But the true C++ way:

std::string charTime = "TIME", buf = "SOMETHINGELSE";
bool equal = (charTime == buf);

Using == does not work because it tries to compare the addresses of the first character of each array (obviously, they do not equal). It won't compare the content of both arrays.




回答2:


In c you could use the strcmp function from string.h, it returns 0 if they are equal

#include <string.h>

if( !strcmp( charTime, buf ))



回答3:


In an expression using == the names of char arrays decay into char* pointing to the start of their respective arrays. The comparison is then perform in terms of the values of the pointers themselves and not the actual contents of the arrays.

== will only return true for two pointers pointing to the same location and false otherwise, even if they are pointing to two arrays with identical contents.

What you need is the standard library function strcmp. This expression evaluates as true if the arrays contain the same contents (up to the terminating null character which must be present in both arrays fro strcmp to work safely).

strcmp(charTime, buf) == 0



回答4:


Check them in a for loop. Get the ASCII numbers for each char once they change they're not equal.




回答5:


You are checking the identity charTime and buf. To check the equality, loop over each character in one array and compare them with the related character in the other array.



来源:https://stackoverflow.com/questions/2440420/compare-equality-of-char-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!