您的代碼不是C.
如果它是C,tab
將指針數組的數組NSString的(無論是)。
在C中,指向NSString的指針數組不一定與指向void的指針兼容...所以刪除了這些類型並獲取類型正確的。
在C,這個工程......
#include <stdio.h>
static char *kStringTab[][2] = {
{"string1", "1"},
{"string2", "1"},
{"string3", "0"},
{"string4", "0"},
{"string5", "1"},
{"string6", "1"},
{NULL, NULL},
};
unsigned int tablen(char *tab[][2]) {
unsigned int i = 0;
while (tab[i][0] != NULL) i++;
return i;
}
int main(void) {
printf("%d\n", tablen(kStringTab));
return 0;
}
建議:增加你的編譯器和記警告的警戒線。
編輯:新的通用版本
#include <math.h>
#include <stdio.h>
static double anothertest[][3] = {
{42, 54, -122},
{33, -0.001, 0.001},
{6, 0, 7}, /* 0 in middle: stop condition in nullp2 :) */
{2, 2, 2},
};
static char *kStringTab[][2] = {
{"string1", "1"},
{"string2", "1"},
{"string3", "0"},
{"string4", "0"},
{"string5", "1"},
{"string6", "1"},
{NULL, NULL},
};
int nullp2(const void *elem) {
const double *tmp = elem;
return (fabs(tmp[1]) < 0.000000001);
}
int nullp(const void *elem) {
char (*const *tmp)[2] = elem; /* tmp is a pointer to each element of kStringTab */
return ((*tmp)[0] == NULL);
}
unsigned int tablen(void *x, size_t size,
int (*check)(const void *)) {
char *y = x;
unsigned int i = 0;
while (!check(y)) {
i++;
y += size;
}
return i;
}
int main(void) {
printf("tablen returns %d\n",
tablen(kStringTab, sizeof *kStringTab, nullp));
printf("tablen returns %d\n",
tablen(anothertest, sizeof *anothertest, nullp2));
return 0;
}
你可以看到它running at ideone。
請注意,靜態對象名稱是'kStringTag'(帶有g)和tablen'kStringTab'(帶有b)的參數。 – pmg 2011-05-28 12:18:59
任何不使用NSArray的原因? – Till 2011-05-28 12:43:52
不,但我只是想了解爲什麼它不像我想要的那樣工作 – klefevre 2011-05-28 13:52:10