When you check to see that a pointer points to an existing object by using:
how exactly does the program check the pointer's validity?Code:if (pointer) ...
When you check to see that a pointer points to an existing object by using:
how exactly does the program check the pointer's validity?Code:if (pointer) ...
"Optimal decisions, once made, do not need to be changed." - Robert Sedgewick, Algorithms in C
That is the lazy way of checking to make sure the pointer is not pointing to NULL.
NULL has a defined value of 0. But this only works if you make sure to set your pointers to NULL when you create them.
Code:int * ptr = NULL; ptr = new int[100]; if( ptr == NULL) { cout << "Calling new failed, out of memory"; return; } // ptr is valid now. //do stuff delete [] ptr; //free the mem used
Well, syntax aside, when you call something like if (ptr == NULL), how does the program know if ptr points to valid memory or not since a pointer will always point to some portion of memory?
"Optimal decisions, once made, do not need to be changed." - Robert Sedgewick, Algorithms in C
The pointer does point to a memory address, but C++ allows it to also point to 0 or NULL often to signify a problem or for initialisation purposes.Well, syntax aside, when you call something like if (ptr == NULL), how does the program know if ptr points to valid memory or not since a pointer will always point to some portion of memory?
If the pointer is NULL or 0 then the (ptr == NULL), expression will be (true). Its just a means to an end.
Last edited by Fordy; 12-29-2001 at 02:35 PM.