Given an array of pointers to string literals:
char *textMessages[] = {
\"Small text message\",
\"Slightly larger text message\",
\"A really larg
You should use the strlen() library method to get the length of a string. sizeof will give you the size of textMessages[2], a pointer, which would be machine dependent (4 bytes or 8 bytes).
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.
strlen maybe?
size_t size = strlen(textMessages[2]);
strlen gives you the length of string whereas sizeof will return the size of the Data Type in Bytes you have entered as parameter.
strlen
sizeof
If you want the number computed at compile time (as opposed to at runtime with strlen) it is perfectly okay to use an expression like
sizeof "A really large text message that "
"is spread over multiple lines";
You might want to use a macro to avoid repeating the long literal, though:
#define LONGLITERAL "A really large text message that " \
"is spread over multiple lines"
Note that the value returned by sizeof includes the terminating NUL, so is one more than strlen.
I'll tell you something, as per my Knowledge arrays an pointers are the same thing except when you use sizeof.
When you use sizeof on a pointer it will return always 4 BYTE regardless the thing that pointer points to, but if it used on array it will return How long the array is big in bytes?.
In you example here *textMessage[] is array of pointer so when you use sizeof(textMessage[2]) it will return 4 BYTE because textMessage[2] is a pointer.
I hope it'll be useful for you.