繁体   English   中英

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

[英]Get length of string array of unknown length

我有这个功能:

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

您有两种选择:

  1. 您可以包含第二个参数,类似于:

    int main(int argc, char**argv)

  2. ...或者你可以双重终止列表:

    char* items[] = { "one", "two", "three", NULL }

在C中无法简单地确定任意数组的大小。它需要以标准方式提供的运行时信息。

支持此操作的最佳方法是将函数中数组的长度作为另一个参数。

虽然它是一个非常古老的线程,但事实上你可以使用Glib确定C中任意字符串数组的长度。 请参阅以下文档:

https://developer.gnome.org/glib/2.34/glib-String-Utility-Functions.html#g-strv-length

提供的,它必须是以null结尾的字符串数组。

你必须知道大小。 一种方法是将大小作为第二个参数传递。 另一种方法是同意调用者他/她应该包括一个空指针作为传递的指针数组中的最后一个元素。

那strlen()函数怎么样?

  char *text= "Hello Word";
  int n= strlen(text);
OR
  int n= (int)strlen(text);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM