0

Let's say I have the following:

MyClass *__strong*matches = (MyClass*__strong*)calloc([myArray count], sizeof([MyClass class]));

If I would like to refer to the second pointer in matches, would I write matches[1] or would I write matches[4]? I am confused because I know that pointers take up 4 bytes, but my program crashes due to a memory error if I follow the logic of matches[4] and my program works perfectly when filling matches if I follow the logic of matches[1].

Furthermore, which would apply if I used malloc instead of calloc?

3
  • 1
    2nd pointer is matches[1]. and calloc is correct, it just initializes all memory locations to 0. Commented Aug 2, 2016 at 15:58
  • Thanks @OmidCompSCI! And do you mind explaining internally how that works? Like why that is true? I'm just trying to fully wrap my head around it. Commented Aug 2, 2016 at 16:01
  • Nothing with pointers taking up 4 bytes, pointers POINT to a memory location, they do not take up actual memory you shouldn't at least think of them doing so, rather something else has taken up the memory, but pointers just "stand on top"/point to that thing taken up the memory already. And matches[4], probably doesn't work because your not allocating that much space, I don't know how many places you are allocating, that is up to what [myArray count] is. Commented Aug 2, 2016 at 16:05

1 Answer 1

1

It is matches[1] because the compiler knows from the type (MyClass * __strong *matches) the size of the items (pointers in your case) that the pointer is pointing at and uses that to determine how to compile the index operation.

For comparison consider int x[4] vs. char y[4], indexing does not mean "byte offset 4" from the start of the array but "item 4" where item in this case is an int (probably 4 or 8 bytes) or char (1 byte). You have pointers (probably 4 or 8 bytes) in your "array" and the compiler knows that from the type.

HTH

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.