理解 C 中的 Char 数组相等性 [英] Understanding Char Array equality in C

查看:18
本文介绍了理解 C 中的 Char 数组相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提前对我的无知表示歉意.我不完全理解如何比较 C 中的 char 数组.我最初是用简单的 == 运算符比较 c 中的两个 char 数组.

Sorry in advance for the ignorance. I don't fully understand how to compare char arrays in C. I was originally comparing two char arrays in c with the simple == operator.

所以在 C 函数中,我会做这样的事情.

So in a C function, I would do something like this.

char *a = "test";
char *b = "test";
if (a == b) ..do something

但我读到我应该像这样使用 strcmp 而不是 ==.

But I read that I should be using strcmp instead of == like this.

char *a = "test";
char *b = "test";
if (0 == strcmp(a, b)) ..do something

哪一个是正确的,为什么?另一个在做什么?

Which one is correct and why? What is the other one doing?

推荐答案

if (a == b)

这里你比较的是指针而不是字符串

Here you are comparing pointers and not the strings

strcmp(a, b)

这里是比较字符串

Which one is correct and why? What is the other one doing?

由于有 2 个字符串存储在不同的内存位置,或者如果存储相同的字符串,则可能 a==b 比较指针没有意义.你想要的是比较指针指向的位置的内容.这是由 strcmp() 完成的,这是比较字符串的正确方法.

Since there are 2 strings stored in different memory locations or if the same string is being stored there is possibility a==b comparing pointers doesn't make sense.What you want is to compare the contents of the locations the pointers are pointing to. Which is done by strcmp() and this is the right way to compare the strings.

例如:

#include <stdio.h>

int main(void) {
char *a = "test";
char *b = "test";

printf("%p
 %p",(void *)a,(void *)b);
    return 0;
}

输出是

0x8048540 
0x8048540

所以指针 a 和 b 都指向同一个内存位置 a==b请注意,这里我们比较的不是字符串中的实际字符,而是指针.

So both the pointers a and b are pointing to the same memory location a==b Note that here what we compare is not the actual characters in the string but just the pointers.

我在另一台机器上运行相同的代码,这个字符串的存储位置不同.

I ran the same code on another machine and the locations in which this string was stored was different.

0x4005f8
0x4005fd

所以现在即使字符串可能相同,您也会看到 a != b.因此使用 strcmp() 来比较字符串.

So now even though the strings might be same you see a != b. Hence use strcmp() to compare strings.

这篇关于理解 C 中的 Char 数组相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆