简体   繁体   English

检查指针是否大于0?

[英]Checking if pointer is greater than 0?

I am trying to determine the purpose of checking for a pointer being greater than 0: 我试图确定检查大于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 ? 进行指针算术是否可以将val设置为0?

Is this a simple null pointer check? 这是一个简单的空指针检查吗?

val isn't a pointer; val 不是指针; it's an int , and its value is obtained by dereferencing src . 它是一个int ,其值是通过取消引用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. val只是一个int ,而不是一个指针。

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. 例如,如果src指向0 ,则val将为0 ,而if语句的条件将为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; 此时, val在函数开始时指向 src值; meanwhile src itself now points to the next memory location. 同时src本身现在指向下一个内存位置。

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 . 此处没有检查指针src是否为null的指针,并且它的null(或其他方式)与val存储的值无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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