私はポインターをよりよく理解しようとしているプログラミングの学生です。私が学んだことの 1 つは、ポインターを NULL に設定できることです。私の質問は、これら 2 つのステートメントの違いは何ですか? それぞれが真/偽を返すのはいつですか?
if (some_ptr == NULL)
if (*some_ptr == NULL)
ありがとう!
私はポインターをよりよく理解しようとしているプログラミングの学生です。私が学んだことの 1 つは、ポインターを NULL に設定できることです。私の質問は、これら 2 つのステートメントの違いは何ですか? それぞれが真/偽を返すのはいつですか?
if (some_ptr == NULL)
if (*some_ptr == NULL)
ありがとう!
The first does a comparison against the address of the variable to null, the second dereferences the pointer, getting the value held at it and compares it against null.
The first statement refers to the actual adress the pointer some_ptr is pointing to. In case it's NULL ( the value represented by the define NULL ), it's true, otherwise not.
The latter statement refers to the content at the adress the pointer is pointing to. So if you're having some_ptr point to an integer, and that integer happens to be the same as your null define, the second condition evaluates to true.
最初のメッセージ: some_ptrはNULL ですか
?
2 つ目は
、some_ptr がNULL を指しているものは何か?
The first is you are comparing the pointer itself against NULL, which seems desirable.
The second is that you are first dereferencing the pointer to get the value which is then compared against NULL, like you are comparing an int value to 0. based on your variable name.
For eg: int* x; Here if you like check if x points to NULL then we use the first statement. With the same int* x, if you use the second statement, then you are trying to dereference the pointer and check for the value that x points to. Because NULL is 0 in C, C++ it checks for the value 0 that x points to.
EDIT: Also with the second statement, if x points to NULL, then deferencing a NULL pointer results in a core drop on UNIX.