Home > Back-end >  comparison between char* values
comparison between char* values

Time:09-24

I am learning c programming at school, and having a question about char*. I initialized char* str5 and char* str6, and their values are the exact same. what I want to confirm is that if I compare them in if statement, is it always comparing its addresses? If so, Why?

char* str5 = "hold";
  printf("str5: %s\n", str5, str5);


  char* str6 = "hold";

  if (str5 == str6){
    printf("str5 and str6 point to the same address\n");
  }  
  else{
    printf("str5 and str6 point to different addresses\n");

  }    

I appreciate any feedback, thank you so much!

CodePudding user response:

Strings aren't a built-in type in C. What you have are two variables of type char *, each of which contains the address of the first character of a string constant.

So when you compare str5 with str6 using ==, you're comparing two addresses.

If you want to compare two strings for equality, you need to use the strcmp function.

CodePudding user response:

While declaring any data types variables in C each variable takes memory. So when I take two variables they will store on different locations in memory.

char *someStr1;
char *someStr2;

Both are of type char* each having two same type of memory on different locations.

So they are not equal all the time .

As dbush said in answer if you want to compare any two strings data they you can use strcmp

char str1[] = "stack";
char str2[] = "overflow";
strcmp(str1, str2);
  • Related