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

标签 c pointers arrays

我有这个功能:

int setIncludes(char *includes[]);

我不知道 includes 将采用多少个值。它可能需要 includes[5],也可能需要 includes[500]。那么我可以使用什么函数来获取 includes 的长度呢?

最佳答案

没有。这是因为数组在传递给函数时会衰减为指向第一个元素的指针。

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


首先,“传递长度”选项。用类似的东西调用你的函数:

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.

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

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

我见过的另一种方法(主要用于整数数组)是使用第一项作为长度(类似于 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);

关于c - 获取未知长度的字符串数组的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3783562/

相关文章:

c - 链接列表不保留递归函数调用中的值?

C语言中的CPU利用率

java - 更短的代码(数组/If 语句)

arrays - 使用正则表达式拆分字符串以将子字符串存储在映射中的分隔符内以创建键值对

c - GCC 是否检查数组边界?

c - Makefile 总是重新编译某些部分

c - 指针声明/引用后的方括号

c - 在 C 指针中反转字符串?

c++ - 为二叉搜索树创建一个新节点

javascript - 使用 spread 元素合并 javascript 数组中的值