smaili smaili - 1 year ago 66
iOS Question

Getting the length of a static C array in Objective C

I have a static array of

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,
are not valid, so I've tried using

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 Source

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);