-2

A strange thing is happening in my app. I have the following NSInteger:

NSInteger *contentStart;

Then in viewDidLoad, I did:

contentStart=0;

Then in another method, I did:

contentStart = contentStart + 20;
NSLog(@"%d", (int)contentStart);

The output is 160 instead of 20!

I tried everything, I even tried contentStart+=20, which gives the same result.

Can anyone tell me what's going on here? I'm going crazy with this.

Many thanks.

ArtSabintsev
  • 5,170
  • 10
  • 41
  • 71
ANA
  • 282
  • 2
  • 16

4 Answers4

3

The issue is that you are adding 20 * sizeof(NSInteger) as contentStart is of type NSInteger *, so you are doing pointer arithmetic.

I assume you are building for 64-bit where sizeof(NSInteger) == 8.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
3

NSInteger* is pointer at NSInteger variable. When you do contentStart + 20 that mean, that you move pointer at 20 NSInteger's. Look's like you have 64bit environment. In 64 environment one NSInteger require 8 bytes. So 8 * 20 = 160; That's why value at contentStart changed at 160 instead 20.

This is calculation with pointers.

Cy-4AH
  • 4,370
  • 2
  • 15
  • 22
  • so if OP were to `[NSLog(@"%d", (int)&contentStart)];`, would that work? By dereferencing the pointer? – A O May 18 '15 at 14:36
  • 1
    @MattyAyOh, no, it will print trimmed to 32 bits `contentsStart`'s address. `int8_t* contentStart;` also will give expected result. – Cy-4AH May 18 '15 at 14:40
  • Pardon my pestering-- I could probably spin up a sample app to figure this stuff out... but I already have SO open :) Okay I got the first part, for the second part, why would a pointer to int8_t work but not an NSInteger when dereferencing? – A O May 18 '15 at 14:45
  • 1
    Like trojanfoe wrote: `sizeof(NSInteger) == 8`. And `sizeof(int8_t) == 1` - one byte. So moving pointer at 20 `int8_t` will move pointer at 20 bytes. But when you do arithmetics you should use normal variables, not pointers. Using pointers may be useful for example when you parse binary data flow for archiving or encryption. – Cy-4AH May 18 '15 at 14:52
2

Because of sizeof(NSInteger) is 8 bytes, you are shifting your pointer by 20 * sizeof(NSInteger) which is equal 160

l0gg3r
  • 8,864
  • 3
  • 26
  • 46
-2

Replace

NSInteger *contentStart;

With

NSInteger contentStart;

And you're good to go :)

Explanation

NSInteger is a primitive type, which means it can be stored locally on the stack. You don't need to use a pointer to access it.

For those who wants a full explanation, you can see this answer

Community
  • 1
  • 1
Fadi Obaji
  • 1,454
  • 4
  • 27
  • 57