Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Char Array equality in C

Tags:

arrays

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.

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?

like image 670
Josh Wang Avatar asked Jan 08 '23 22:01

Josh Wang


1 Answers

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.

like image 149
Gopi Avatar answered Jan 16 '23 11:01

Gopi