简体   繁体   English

NSInteger = NSInteger -1?

[英]NSInteger = NSInteger -1?

I am trying to do a very simple thing but I can't figure out how; 我想做一件非常简单的事,但我无法弄清楚如何;

NSInteger * a=10;
a=a-1;
NSlog(@"a=%d",a);

For some reason it's showing a=6 . 由于某种原因,它显示a=6

How can it be? 怎么可能?

Your problem is that you've declared the variable a as a pointer. 您的问题是您已将变量a声明为指针。 Most Objective-C variables are pointers, but NSInteger is an exception, because it's just typedef 'd to int or long . 大多数Objective-C变量都是指针,但NSInteger是一个例外,因为它只是对intlong typedef

Your code should look like this: 您的代码应如下所示:

NSInteger a=10;
a=a-1;
NSlog(@"a=%d",a);

When you do math on a pointer, you are actually moving the location in memory it points to. 当您对指针进行数学运算时,实际上是在移动它所指向的内存中的位置。 For example if the size of an NSInteger is 4 ( sizeof(NSInteger) == 4 ), moving it -1, or in other words, a one structure size back, the pointer gets decreased by 4. This mechanique is heavily used in C when iterating arrays of structures, eg 例如,如果NSInteger的大小为4( sizeof(NSInteger) == 4 ),将其移动-1,或者换句话说,返回一个结构大小,则指针减少4.此机制在C中大量使用当迭代结构数组时,例如

CGPoint myPoints[4];
CGPoint* point = myPoints; //get the first point

for (NSUInteger i = 0; i < 4; i++) {
   CGPoint currentPoint = *point;
   point++; //moves to the next point, adding sizeof(CGPoint)
}

This is called pointer arithmetic and you can write it in different ways, eg pointer + 1 but also point[1] or 1[point] (the last two are actually equal to *(pointer + 1) ). 这称为指针算法,您可以用不同的方式编写它,例如pointer + 1但也point[1]1[point] (最后两个实际上等于*(pointer + 1) )。

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

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