How can I specify that a method should take as parameter a pointer to a location in memory that can hold a specified number of values? For example, if I have:
- (void)doSomethingWith:(int *)values;
I’d like to make it clear that the int * passed in should point to an allocated space in memory that’s able to hold 10 such values.
To directly answer your question, use an array argument with a bounds, e.g.:
Which specifies that the method takes an array of 10 integers.
Only problem is the C family of languages do not do bounds checking, so the following is valid:
So while you are specifying the size, as you wish to do, that specification is not being enforced.
If you wish to enforce the size you can use a
struct:Now this doesn’t actually enforce the size at all[*], but its as close a you can get with the C family (to which the word “enforcement” is anathema).
If you just wish to know the size, either pass it as an additional argument or use
NSArray.[*] It is not uncommon to see structures in C following the pattern:
Such structures are dynamically allocated based on their size (
sizeof(someStruct)) plus enough additional space to store sufficient integers (e.g.n * sizeof(int)).In other words, specifying an array as the last field of a structure does not enforce in anyway that there is space for exactly that number of integers; there may be space for more, or fewer…