www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Checking pointers

reply Trevor Parscal <trevorparscal hotmail.com> writes:
How should i go about checking to see if a pointer is set?

I can set a pointer to null, and also to point to something. So how do I 
check if it is null or not?

int* foo = null;
int bar = 5;
foo = &bar;

if(foo == null)
{
	// don't use it
}
else
{
	// use it
}

I have tried several things, nothing works so far..

-- 
Thanks,
Trevor Parscal
www.trevorparscal.com
trevorparscal hotmail.com
Jun 01 2005
next sibling parent Sean Kelly <sean f4.ca> writes:
In article <d7kfom$1p4q$1 digitaldaemon.com>, Trevor Parscal says...
How should i go about checking to see if a pointer is set?

I can set a pointer to null, and also to point to something. So how do I 
check if it is null or not?

int* foo = null;
int bar = 5;
foo = &bar;

if(foo == null)
{
	// don't use it
}
if(foo == null) works just fine, though it could cause problems with template code (since comparing a class reference to null can cause an access violation). The alternate that always works is if(foo). Sean
Jun 01 2005
prev sibling next sibling parent zwang <nehzgnaw gmail.com> writes:
Trevor Parscal wrote:
 How should i go about checking to see if a pointer is set?
 
 I can set a pointer to null, and also to point to something. So how do I 
 check if it is null or not?
 
 int* foo = null;
 int bar = 5;
 foo = &bar;
 
 if(foo == null)
 {
     // don't use it
 }
 else
 {
     // use it
 }
 
 I have tried several things, nothing works so far..
 
You've answered your own question. Either "foo is null" or "foo === null" would do. "foo == null" is also okay for pointers of primitive types.
Jun 01 2005
prev sibling parent pragma <pragma_member pathlink.com> writes:
In article <d7kfom$1p4q$1 digitaldaemon.com>, Trevor Parscal says...
How should i go about checking to see if a pointer is set?

I can set a pointer to null, and also to point to something. So how do I 
check if it is null or not?

int* foo = null;
int bar = 5;
foo = &bar;

if(foo == null)
{
	// don't use it
}
else
{
	// use it
}

I have tried several things, nothing works so far..
Have you tried the 'is' operator? if(foo is null){ /* blah */ } - EricAnderton at yahoo
Jun 01 2005