获取未知长度的字符串数组的长度

Moh*_*nde 9 c arrays pointers

我有这个功能:

int setIncludes(char *includes[]);
Run Code Online (Sandbox Code Playgroud)

我不知道includes会有多少价值.它可能需要includes[5],可能需要includes[500].那么我可以使用什么功能来获得长度includes

pax*_*blo 16

空无一人.那是因为当传递给函数时,数组会衰减到指向第一个元素的指针.

您必须自己传递长度或使用数组本身中的某些内容来指示大小.


首先,"传递长度"选项.用以下内容调用您的函数:

int setIncludes (char *includes[], size_t count) {
    // Length is count.
}
:
char *arr[] = {"Hello,", "my", "name", "is", "Pax."};
setIncludes (arr, sizeof (arr) / sizeof (*arr));
setIncludes (arr, 2); // if you don't want to process them all.
Run Code Online (Sandbox Code Playgroud)

sentinel方法在末尾使用一个特殊值来表示没有更多的元素(类似于\0C char数组的末尾以表示字符串),并且将是这样的:

int setIncludes (char *includes[]) {
    size_t count = 0;
    while (includes[count] != NULL) count++;
    // Length is count.
}
:
char *arr[] = {"Hello,", "my", "name", "is", "Pax.", NULL};
setIncludes (arr);
Run Code Online (Sandbox Code Playgroud)

我见过的另一种方法(主要用于整数数组)是使用第一项作为长度(类似于Rexx词干变量):

int setIncludes (int includes[]) {
    // Length is includes[0].
    // Only process includes[1] thru includes[includes[0]-1].
}
:
int arr[] = {4,11,22,33,44};
setIncludes (arr);
Run Code Online (Sandbox Code Playgroud)