smaili smaili - 6 months ago 17
iOS Question

Getting the length of a static C array in Objective C

I have a static array of

NSString
defined in my implementation file like so:

NSString * const knames[] = { @"", @"", @"", ..., @"" };


and what I'd like to do is get the length dynamically. Since this is a C array,
length
and
count
are not valid, so I've tried using
sizeof
:

int count = (sizeof knames) / (sizeof knames[0]);


However, it results in the error message:
Invalid application of 'sizeof' to an incomplete type 'NSString *const _strong[]'
Any suggestions?

Answer

Small typo; sizeof requires brackets:

/*const?*/ int count = sizeof(knames) / sizeof(knames[0]);

You could create a macro somewhere globally:

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
...

const int count = ARRAY_SIZE(knames);