简体   繁体   中英

Get length of string array of unknown length

I have this function:

int setIncludes(char *includes[]);

I don't know how many values includes will take. It may take includes[5] , it may take includes[500] . So what function could I use to get the length of includes ?

There is none. That's because arrays will decay to a pointer to the first element when passing to a function.

You have to either pass the length yourself or use something in the array itself to indicate the size.


First, the "pass the length" option. Call your function with something like:

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.

A sentinel method uses a special value at the end to indicate no more elements (similar to the \\0 at the end of a C char array to indicate a string) and would be something like this:

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

Another method I've seen used (mostly for integral arrays) is to use the first item as a length (similar to Rexx stem variables):

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

You have two options:

  1. You can include a second parameter, similar to:

    int main(int argc, char**argv)

  2. ... or you can double-null terminate the list:

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

There is no way to simply determine the size of an arbitrary array like this in C. It requires runtime information that is not provided in a standard way.

The best way to support this is to take in the length of the array in the function as another parameter.

Though it is a very old thread, but as a matter of fact you can determine the length of an arbitrary string array in C using Glib. See the documentation below:

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

Provided, it must be null terminated array of string.

You have to know the size either way. One way would be to pass the size as a second parameter. Another way is to agree with the caller the he/she should include a null pointer as the last element in the passed array of pointers.

And what about strlen() function?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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