了解用C字符数组平等 [英] Understanding Char Array equality in C

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

问题描述

对不起,提前为无知。我不完全了解如何字符数组中C.比较我本来在比较C两个字符数组用简单的 == 运营商。

因此​​,在C函数中,我会做这样的事情。

 的char * A =测试;
char *之B =测试;
如果(A == B)..对

不过,我读,我应该使用 STRCMP 而不是 == 是这样的。

 的char * A =测试;
char *之B =测试;
如果(0 == STRCMP(A,B))..对

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


解决方案

 如果(A == B)

下面你比较指针,而不是字符串

  STRCMP(A,B)

下面你比较字符串

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

既然有存储在不同的存储单元2串,或者相同的字符串被存储有可能性 A == b 比较指针不作sense.What你想要的是比较指针指向单元的内容。这是由的strcmp(),这是比较字符串以正确的方式完成的。

例如:

 的#include<&stdio.h中GT;诠释主要(无效){
字符* A =测试;
char *之B =测试;的printf(%P \\ N%P(无效*)A,(无效*)B);
    返回0;
}

的输出是

  0x8048540
0x8048540

因此​​,无论指针a和b都指向同一个内存位置 A == b
注意,这里我们比较的不是字符串中的实际字符只是指针。

我跑到另一台机器上同一code和在此字符串储存是不同的位置。

  0x4005f8
0x4005fd

所以,现在即使字符串可能是相同的,你看到 A!= B
因此,使用的strcmp()比较字符串。

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.

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

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

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)

Here you are comparing strings

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

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.

For example :

#include <stdio.h>

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

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

The output is

0x8048540 
0x8048540

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

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

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

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