簡體   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