为什么总是得到相同的布尔值

Why always get the same boolean value?

本文关键字:布尔值 为什么      更新时间:2023-10-16
#include<stdio.h>
#include<stdlib.h>
int main ( void )
{
     bool* Str_A = (bool*)calloc(1024,1);
     bool* Str_B = (bool*)calloc(1024,1);
     *Str_A = true;
     *Str_B = true;
     *(Str_A+2) = *Str_A+*Str_B;
     printf("%s", (Str_A+2)?"true":"false");
}

无论我是否将*Str_A或/和*Str_B更改为false,它总是打印true.为什么?

这一行:

printf("%s", (Str_A+2)?"true":"false");
如果

Str_A 加 2 的地址不为零,则true打印。您要检查的是 Str_A 加 2 的内容是否不为零,因此您应该编写:

printf("%s", *(Str_A+2)?"true":"false");

或者我更喜欢:

printf("%s", Str_A[2]?"true":"false");

在表达式 (Str_A+2)?"true":"false" 中,Str_A+2 是一个指针,因为它不是空指针,所以它被转换为 true