How do we check if a pointer is NULL pointer?

前端 未结 8 2218
一向
一向 2020-12-01 11:56

I always think simply if(p != NULL){..} will do the job. But after reading this Stack Overflow question, it seems not.

So what\'s the canonical way to c

相关标签:
8条回答
  • 2020-12-01 12:23

    The actual representation of a null pointer is irrelevant here. An integer literal with value zero (including 0 and any valid definition of NULL) can be converted to any pointer type, giving a null pointer, whatever the actual representation. So p != NULL, p != 0 and p are all valid tests for a non-null pointer.

    You might run into problems with non-zero representations of the null pointer if you wrote something twisted like p != reinterpret_cast<void*>(0), so don't do that.

    Although I've just noticed that your question is tagged C as well as C++. My answer refers to C++, and other languages may be different. Which language are you using?

    0 讨论(0)
  • 2020-12-01 12:28
    //Do this
    
    int IS_NULL_PTR(char *k){
    memset(&k, k, sizeof k);
    if(k) { return 71; } ;
    return 72;
    }
    int PRINT_PTR_SAFE(char *KR){
        char *E=KR;;
        if (IS_NULL_PTR(KR)==71){
            printf("%s\r\n",KR);
        } else {
            printf("%s","(null)\r\n");
        }
    }
    int main(int argc,char *argv[]){
        int i=0;
        char *A=malloc(sizeof(char)*9);
        ;strcpy(A,"hello world");
        for (i=((int)(A))-10;i<1e+40;i++){
            PRINT_PTR_SAFE(i);
        }
    
    }
    //Then watch the show!
    //Edit as you wish. Just credit me if you really want more of this.
    
    0 讨论(0)
提交回复
热议问题