简体   繁体   中英

Checking if pointer is greater than 0?

I am trying to determine the purpose of checking for a pointer being greater than 0:

void someFunction(int *src) {
   int val = *src++;
   if( val > 0 ) {
       // Do something?
   }
}

If the data type is pointer, wouldn't the value of the pointer always be a memory address? Does doing pointer arithmetic do something that may set val = 0 ?

Is this a simple null pointer check?

val isn't a pointer; it's an int , and its value is obtained by dereferencing src .

你不检查,如果指针> 0,则检查是否在举办地点指向的值大于0 src单独将是一个地址, *src是在那个地址保存的值。

That's not checking if a pointer is greater than zero; it's checking if the pointed-to value is greater than zero, and simultaneously advancing the pointer by one. Here's some equivalent code that might help you understand:

void someFunction(int *src) {
   int val = *src; // Dereferencing the pointer
   src++;          // Moving the pointer

   if( val > 0 ) {
       // Do something?
   }
}

val is just an int , not a pointer.

That's not checking a pointer, it's checking an integer. The * operator dereferences the pointer, yielding the value the pointer is currently pointing at. For example, if src is pointing at a 0 , val will be 0 and the condition of that if statement will be false.

Take a closer look at the line that's giving you trouble:

int val = *src++;

You ought to recognize that as the postfix increment operator at work, so we can split that line in two:

int val = *src;
++src;

At this point, val has a copy of the value src pointed to at function's start; meanwhile src itself now points to the next memory location.

There is nothing here that checks whether the pointer src is null, and its nullness (or otherwise) has no bearing on what value is stored in val .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM