Determining the Length of a String Literal

后端 未结 7 1715
栀梦
栀梦 2020-12-16 12:45

Given an array of pointers to string literals:

char *textMessages[] = {
    \"Small text message\",
    \"Slightly larger text message\",
    \"A really larg         


        
7条回答
  •  感动是毒
    2020-12-16 13:26

    You could exploit the fact, that values in an array are consecutive:

    const char *messages[] = {
        "footer",
        "barter",
        "banger"
    };
    
    size_t sizeOfMessage1 = (messages[1] - messages[0]) / sizeof(char); // 7   (6 chars + '\0')
    

    The size is determined by using the boundaries of the elements. The space between the beginning of the first and beginning of the second element is the size of the first.

    This includes the terminating \0. The solution, of course, does only work properly with constant strings. If the strings would've been pointers, you would get the size of a pointer instead the length of the string.

    This is not guaranteed to work. If the fields are aligned, this may yield wrong sizes and there may be other caveats introduced by the compiler, like merging identical strings. Also you'll need at least two elements in your array.

提交回复
热议问题