0

I am trying to solve the problem caused by this question. The code that I wrote to show the problem can be seen below. I used strcpy to copy one global string to a string created with memset. Although their contents seem the same, the result says they are not; as the if statement at the end is not executed.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MSG "mystr"

int main() {
  char buffer[6];
  memset (buffer, 0x00, 6);
  strcpy(buffer,MSG);
  printf("Buffer is %s.\n", buffer);
  printf("MSG is %s.\n", MSG);
  if (buffer == MSG) printf("True \n");
  return 0;
}

And the result is;

Buffer is mystr.
MSG is mystr.

I would be appreciated if you show me where I am doing wrong.

1 Answers1

4

Equality check in C for strings isn't done this way! What the check you're doing is it compares the adresses in memory the two pointers point to, and if they are equal, it will return true. In this case they aren't so it returns false.

You need to use strcmp for this. strcmp returns either -1, 0, 1 depending on which of the compared strings have a value less than the other. If they are equal, it will return 0. You can read more about it here: strcmp

SenselessCoder
  • 1,139
  • 12
  • 27