Home > other >  how to get length of string array
how to get length of string array

Time:03-13

char* c[] = { "abc","abcde","abcdef","abcdefg" };

I used sizeof(c[0]) to get string's length but not work. any other method to get array string length? like abc = 3,abcde = 5.

CodePudding user response:

As with any defined array, you can get the number of elements with:

char *c[] = { "abc", "abcde", "abcdef", "abcdefg" };
size_t c_len = sizeof(c) / sizeof(c[0]);  // 4 elements

Note that sizeof(c[0]) is the size of the array element, a pointer to char (char *) which you initialize with a pointer to a string constant that must not be changed. The type for this array should be:

const char *c[] = { "abc", "abcde", "abcdef", "abcdefg" };

There is no compile time method to get the length of these strings, you must use strlen(). But you can get the lengths of explicit string literals with sizeof this way:

const char *c[] = { "abc", "abcde", "abcdef", "abcdefg" };
size_t len[] = { sizeof("abc") - 1, sizeof("abcde") - 1, sizeof("abcdef") - 1, sizeof("abcdefg") - 1 };
  •  Tags:  
  • c
  • Related