Consider the following array of "strings" in C:
const char* const animals[] =
{
"",
"Cat",
"Dawg",
"Elephant",
"Tiger",
};
Is it possible to obtain:
The number of elements (char pointers) in the
animalsarray?The length of each array member, ie. size = 1 for element 0, size = 4 for element 1 and so on?
I tried using sizeof of course, but it doesnt seem to return anything that makes sense. I think it should be possible for the precompiler to figureout the amount of elements in the array as well as size of each element. For the latter, one could serach of \0 character as well do define length. I wonder however why I cant get proper array size (ie. number of elements in animals array) when using sizeof?
I would appreciate all suggestions.
Edit:
Yes I meant preprocessor, not precompiller, sorry.
Why do I need this functionality? I am parsing incoming strings from a serial port. I need to figure out either the received string matches any string in my preconfigured table. If it does, I need the index of that item. I need the searching algorithm to be fast. Because of that, I first want to check the string size and all bytes after that, only if size matches. Because of that I thought maybe the length of each string is known at compile time.
This is my current checking function:
static int32_t getStringIndex(const uint8_t* const buf, const uint32_t len)
{
if (!len)
return -1;
int32_t arraySize = sizeof(animals) / sizeof(animals[0]);
uint32_t elementSize;
// The algorithm 1st checks if the length matches. If yes, it compares the strings.
for (int32_t i = 0; i < arraySize; i++)
{
elementSize = strlen(animals[i]);
if (elementSize == len)
{
if (0 == memcmp(animals[i], buf, len))
{
return i;
}
}
}
return -1;
}
I dont use strcmp because buf doesnt have \0 at the end.
sizeof(animals)/sizeof(*animals)to get the number of animals (including the initial, "empty" animals which you probably shouldn't have). You can usestrlen(animals[i])to get the lengths of the individual animal names.animalsonce and for all during the initialisation of the program, so you don't need to callstrlenover and over. I don't think you can get the length of a string literal in an array (e.g.sizeof(animals[2])won't be the length of the strig but the size of a pointer).