简体   繁体   English

为什么 assert(str?=NULL) 不返回错误

[英]why assert(str!=NULL) does not return an error?

Why did this not print an assert error?为什么这没有打印断言错误?

This is my code:这是我的代码:

#include<assert.h>
#include<stdio.h>

int main(){
    int n =12;
    char str[50] = "";
    assert(n>=10);
    printf("output :%d\n",n);
    assert(str!=NULL);
    printf("output :%s\n",str);
}
char str[50] = "";

This makes str into an array of 50 chars, and initialises the memory to all zeroes (first byte explicitly from "" and rest implicitly, because C does not support partial initialisation of arrays or structs). This makes str into an array of 50 chars, and initialises the memory to all zeroes (first byte explicitly from "" and rest implicitly, because C does not support partial initialisation of arrays or structs).


assert(str!=NULL);

When used in an expression, array is treated as pointer to its first element.在表达式中使用时,数组被视为指向其第一个元素的指针。 The first element of the array very much has an address, so it is not NULL .数组的第一个元素有一个地址,所以它不是NULL


If you want to test if the first element of the array is 0, meaning empty string you need如果要测试数组的第一个元素是否为 0,即需要空字符串

assert(str[0] != '\0');

You could compare to 0 , or just say assert(*str);您可以与0进行比较,或者只是说assert(*str); , but comparing to character literal '\0' makes it explicit to the reader of the code, that you are probably testing for string-terminating zero byte, not some other kind of zero, even if for the C compiler they're all the same. ,但是与字符文字'\0'相比,代码的读者可以清楚地看到,您可能正在测试以字符串结尾的零字节,而不是其他类型的零,即使对于 C 编译器它们都是相同的。

str is an array which is effectively a pointer, which means the address in memory where the array is stored. str 是一个数组,实际上是一个指针,这意味着 memory 中存储数组的地址。 A pointer is NULL if it doesn't point to any specific place in memory.如果指针不指向 memory 中的任何特定位置,则该指针为 NULL。 Your str pointer is not null, it points to a place in memory containing an array of 50 elements.您的 str 指针不是 null,它指向 memory 中包含 50 个元素的数组的位置。

That array is an array of chars, otherwise known as a string.该数组是一个字符数组,也称为字符串。 You initialise it to an empty string but it's still there and the pointer to it (str) is still a valid, non-NULL pointer.您将它初始化为一个空字符串,但它仍然存在并且指向它的指针 (str) 仍然是一个有效的非 NULL 指针。

str.=NULL does not mean "str is not an empty string" It means "str is not an undefined pointer" str.=NULL 并不意味着“str 不是空字符串” 它意味着“str 不是未定义的指针”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM