What would be a proper invalid value for a pointer?

旧城冷巷雨未停 提交于 2019-12-20 05:27:08

问题


Suppose I have this code. Your basic "if the caller doesn't provide a value, calculate value" scenario.

void fun(const char* ptr = NULL)
{
   if (ptr==NULL) {
      // calculate what ptr value should be
   }
   // now handle ptr normally
}

and call this with either

fun();          // don't know the value yet, let fun work it out

or

fun(something); // use this value

However, as it turns out, ptr can have all kinds of values, including NULL, so I can't use NULL as a signal that the caller doesn't provide ptr.

So I'm not sure what default value to give ptr now instead of NULL. What magic value can I use? Does anybody have ideas?


回答1:


void fun()
{
   // calculate what ptr value should be
   const char* ptr = /*...*/;

   // now handle ptr normally
   fun(ptr);
}



回答2:


Depending on your platform, a pointer is likely either a 32 or 64-bit value.

In those cases, consider using:

0xFFFFFFFF or  0xFFFFFFFFFFFFFFFF

But I think the bigger question is, "How can NULL be passed as a valid parameter?"

I'd recommend instead having another parameter:

void fun(bool isValidPtr, const char* ptr = NULL)

or maybe:

void fun( /*enum*/ ptrState, const char* ptr = NULL)



回答3:


I agree with all the other answers provided, but here's one more way of handling that, which to me personally looks more explicit, if more verbose:

void fun()
{
  // Handle no pointer passed
}

void fun(const char* ptr)
{
  // Handle non-nullptr and nullptr separately
}



回答4:


You should use the nullptr for that. Its new in the C++11 standart. Have a look here for some explanation.




回答5:


Using overloaded versions of the same function for different input is best, but if you want to use a single function, you could make the parameter be a pointer-to-pointer instead:

void fun(const char** ptr = NULL) 
{ 
   if (ptr==NULL) { 
      // calculate what ptr value should be 
   } 
   // now handle ptr normally 
} 

Then you can call it like this:

fun();

.

char *ptr = ...; // can be NULL
fun(&ptr);



回答6:


If you want a special value that corresponds to no useful argument, make one.

header file:

extern const char special_value;

void fun(const char* ptr=&special_value);

implementation:

const char special_value;

void fun(const char* ptr)
{
    if (ptr == &special_value) ....
}



回答7:


1?

I can't imagine anyone allocating you memory with that address.



来源:https://stackoverflow.com/questions/10489211/what-would-be-a-proper-invalid-value-for-a-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!