0
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.

2
  • Can you please clarify what you mean by "length of string array"? I think you mean the number of strings in the array but the reference to sizeof(c[0]) is confusing as there is no way looking at one element can get you the full size. If it is indeed num strings in array use sizeof(c)/sizeof(c[0]) Commented Mar 13, 2022 at 6:43
  • 1
    Oh, your update implies you want strlen(c[i]) where i is the index of the array entry you want the length for. Commented Mar 13, 2022 at 6:45

1 Answer 1

2

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 };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.