当p指向一个字符时,strcmp(p,"\n")是不确定的行为吗?

gsa*_*ras 2 c string pointers c99 undefined-behavior

检查最小值:

#include <stdio.h>
#include <string.h>

int main(void) {
    char newline = '\n';
    char* p = &newline;
    if(strcmp(p, "\n") == 0) {
        printf("ok\n");
    } else {
        printf("wrong\n");
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

是不确定的行为?或者它是完全错误的(即它总是返回不相等)?无论是什么,请解释原因!

dje*_*lin 5

它是UB,原因p很简单,它不是以空字符结尾的字符串,strcmp如果输入非空终止字符串,则为UB.