1

I am trying to compare 2 strings using the below code:

char a[100] = "\0"; char* b[10]; for (int i = 0; i < 10; i++) b[i] = ""; b[0] = "xy"; a[0] = 'x'; a[1] = 'y'; int c = strcmp(a, b[0]); 

I think both a and b[0] contain the string "xy", so I expect int c equal 0. However the result stored in int c is -858993460. Why would that happen? What should I do in order to avoid this fault? Thank you very much.

Update: I found that there is some error on my computer...

char a[3] = { NULL }; char d[3] = { NULL }; a[0] = 'x'; a[1] = 'y'; a[2] = '\0'; d[0] = 'x'; d[1] = 'y'; d[2] = '\0'; int c = strcmp(a, d); 

Even using this code, I got int c to be a negative value. I have no idea why that happened.

7
  • 1
    Strings in C are null terminated. When you compare strings means two null terminated strings. Commented Mar 21, 2018 at 10:09
  • I'm pretty sure it's a duplicate. Anyone? Commented Mar 21, 2018 at 10:25
  • this one? stackoverflow.com/questions/28997095/… Commented Mar 21, 2018 at 10:27
  • 1
    Placing the code into a `main() and feeding to a C compiler cannot reproduce the behaviour. Commented Mar 21, 2018 at 11:40
  • 1
    Please include a minimal reproducible example which includes the part where you print the value of c. I strongly suspect that you are printing the value of some other (unitialised) variable. Commented Mar 21, 2018 at 13:41

1 Answer 1

2

It is undefined behaviour because a is not null terminated. All string in C have to be null terminated to be used in strcmp. What strcmp does is looping over the two strings until either one of the two is NULL terminated (see Implementation of strcmp to get an idea of how it works). You can see that if '\0' is not present anywhere you got a problem there.

Read Why do strings in C need to be null terminated? for more info:

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.