You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS2017中指针空值检查行为异常问题求助

问题根源:if语句后的多余分号!

嘿,别担心,这个问题和你创建的是空项目还是控制台项目完全没关系——问题出在你代码里的两个小细节上:if语句后面多了分号!

咱们来拆解一下:在C语言里,if(条件); 这个分号表示「条件判断后什么都不做」,后面跟着的大括号{}会被当成完全独立的代码块,不管if的条件是否成立,都会无条件执行。

看你的代码:

if (Bptr == NULL); {printf("Bptr is still a null pointer: %p\n", Bptr); };
if (!Bptr); {printf("Bptr is still a null pointer (check 2): %p\n", Bptr); };

这两行里的分号让if的判断完全失效了——哪怕Bptr已经被赋值为&Barray(不是NULL),后面的printf还是会跑,所以才出现了「明明Bptr有地址,却输出它是NULL指针」的矛盾结果。

修正后的代码

把两个if后面的分号删掉就行:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main(const int argc, const char *argv[]) {
    double *Bptr = NULL;
    printf("Bptr's current value is: %p\n", Bptr);
    double Barray = 1.02;
    Bptr = &Barray;
    if (Bptr == NULL) {printf("Bptr is still a null pointer: %p\n", Bptr); }
    if (!Bptr) {printf("Bptr is still a null pointer (check 2): %p\n", Bptr); }
    printf("The address of Bptr is: %p\n", Bptr);
    return 0;
}

修正后的预期输出

这样运行后,两个if的条件都不成立,不会执行里面的printf,输出会变成:

Bptr's current value is: 00000000
The address of Bptr is: 00B3FD58

(地址部分可能因环境不同而变化)

下次写if语句的时候可要注意别多加分号啦,这种小语法错误很容易迷惑人,但找到根源就很简单啦!

内容的提问来源于stack exchange,提问作者Floris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:52:10