1

I want to pass an array of long long to an objective c function. I would like the array to be passed as a pointer, if possible, so that copying is not done. I wrote this code:

+ (int) getIndexOfLongLongValue: (long long) value inArray: (long long []) array size: (int) count
{
    for (int i =0; i < count; i++)
    {
       if (array[i] == value)
           return i + 1;
    }
    return 0;
}

to which I pass

long long varname[count];

as the second argument. I am wondering if I can pass this array as a pointer or if this method is fine. I don't need pointers to long longs but pointers to the array.

user1122069
  • 1,767
  • 1
  • 24
  • 52

3 Answers3

2

C arrays always decay to pointers when passed to a function or a method, so it is not copied in your example. A pointer to long long is automatically a pointer to an array of long long, by virtue of the operator [] being applicable to all pointers. Since your method does not modify the array, you may want to add const to highlight this fact in your API; other than that, your method is fine.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

It is being passed in as a pointer (language pedantry notwithstanding); nothing's getting copied. type[] is, for the most part, the same thing as type*.

To confirm this, check out sizeof(array) in the method. You'll see it's the same size as sizeof(void*).

If you really want a pointer to the array, i.e. a pointer to a pointer to the long longs, you'll need to use something like type**; but the only reason to want to do this is if you want to modify the underlying array pointer from the method, which is hardly ever the case.

David Given
  • 13,277
  • 9
  • 76
  • 123
  • Thanks, but I still don't understand fully. Lets say I have an array of 1000 items (as an example) and I pass it into this function. Does the memory used increase only by the size of one pointer - 4-8 bytes? – user1122069 Jul 14 '12 at 16:36
  • (long long *)array is the same as (long long []) array? – user1122069 Jul 14 '12 at 16:40
  • The array lives on the heap (usually). When you call the function, all you pass in is a pointer --- the location of the array. (It's actually quite hard to pass an array by value in C/C++/Objective C; you won't do it by accident.) Both `long long*` and `long long[]`, when used as parameter types, represent pointers. – David Given Jul 14 '12 at 19:14
0

Objective-C is just an extremely thin wrapper around regular C, so this is handled the same as it would be handled in C: passing by reference.

+ (int)getIndexOfLongLongValue:(long long)value inArray:(long long *)array size:(int)count
{
    for (int i = 0; i < count; i++)
    {
        if (array[i] == value)
            return i + 1;
    }
}

Then in the code that calls the function: int myIndex = [object getIndexOfLongLongValue: aValue inArray: varname size: count];

Rabbit
  • 566
  • 5
  • 13