在线编译器 C

#include <stdio.h> int main() { char s1[1001], s2[1001]; fgets(s1, sizeof(s1), stdin); fgets(s2, sizeof(s2), stdin); int len1 = 0; int len2 = 0; if (s1[len1 - 1] == '\n') s1[len1 - 1] = '\0'; if (s2[len2 - 1] == '\n') s2[len2 - 1] = '\0'; int i = 0; while (s1[i] != '\0' && s2[i] != '\0') { if (s1[i] != s2[i]) { printf("%d\n", i); return 0; } i++; } if (s1[i] == '\0' && s2[i] == '\0') { printf("0\n"); } else { printf("%d\n", i); } return 0; }
The code reads two strings, tries to remove trailing newline characters, and then finds the first index where the strings differ. However, it uses `len1` and `len2` before they are assigned any value, which causes undefined behavior.

- The variables `len1` and `len2` are set to 0, but then you try to access `s1[len1 - 1]` and `s2[len2 - 1]`. Since `len1` and `len2` are 0, `len1 - 1` and `len2 - 1` are negative indices, which is invalid. You need to first compute the actual lengths of the strings using `strlen` or a loop before trying to check for a newline.
- The newline removal logic should only be applied after you know the length of each string. Also, `fgets` includes the newline only if there is space, so you should check if the last character before the null terminator is `'\n'`.