In C it's possible to omit typing array size if it's fields are provided immediately, so the compiler can easily calculate the size by itself. This is presented below, note empty [] parenthesis.
char* sampleArray[] = { "Hello world!", "How are you?", "You like coffe?" };
We can also specify the size directly:
char* sampleArray[2] = { "Hello world!", "How are you?", "You like coffe?" };
Or use the best way:
const int SampleArraySize = 2; char* sampleArray[SampleArraySize] = { "Hello world!", "How are you?", "You like coffe?" };
In the first two examples we don't have a variable that would tell us how many elements the array has. Sure, we may hardcode it, but it's not a good idea from a maintainability point of view.
We may calculate the size of above array by using a simple trick:
int sampleArrayLength = sizeof(sampleArray) / sizeof(sampleArray[0]);
Note that it will work with all built in types and if the size or even the type of an array will be changed in the future, this line will still be correct.
Below you may see a simple use case.
#include <stdio.h> int main() { char* sampleArray[] = { "Hello world!", "How are you?", "You like coffe?" }; int sampleArrayLength = sizeof(sampleArray) / sizeof(sampleArray[0]); printf("someStrings array has %d elments counting from one.\n", sampleArrayLength); for(int i = 0U; i < sampleArrayLength; i++) { printf("#%d element: %s\n", i, sampleArray[i]); } return 0; }
sh-4.3$ main someStrings array has 3 elments counting from one. #0 element: Hello world! #1 element: How are you? #2 element: You like coffe?
Unfortunately, it will not work for arrays passed as pointers - for them, we need to pass size of an array as an additional argument.
0 commentaires:
Post a Comment