3 years late but better late that never.
Short answer
#define length(array) ((sizeof(array)) / (sizeof(array[0])))
Long answer
So using sizeof(array)
returns the size of the type of the array
* the amount of elements
. Knowing this, we could achieve this:
#define length(array) ((sizeof(array)) / (sizeof(array[0])))
and you would use it like:
type yourArray[] = {your, values};
length(yourArray); // returns length of yourArray
For example:
#include <stdlib.h>
#include <stdio.h>
#define length(array) ((sizeof(array)) / (sizeof(array[0])))
int main()
{
const char *myStrings[] = {"Foo", "Bar", "Hello, World!"}; // 3 elements
int myNums[] = {0, 1, 5, 7, 11037}; // 5 elements
char myChars[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g'}; // 7 elements
printf("Length of myStrings array: %lu\n", length(myStrings));
printf("Length of myNums array: %lu\n", length(myNums));
printf("Length of myChars array: %lu\n", length(myChars));
return 0;
/* Output:
Length of myStrings array: 3
Length of myNums array: 5
Length of myChars array: 7 */
}
I tested it and it also works with uninitialized arrays, probably because they contain garbage (from being uninitialized) from the same type. Integer uninitialized arrays contain random integer numbers and const char* uninitialized arrays contain (null) which is treated as a const char*.
Now, this only works with arrays on the stack. Pointers pointing to space reserved in the heap used as an array would give unexpected results. For example:
int *myNums = (int *)malloc(3 * sizeof(int)); // Space for 3 integers
printf("Length of myNums: %lu\n", length(myNums)); // Outputs 2 instead of 3
So be advised. Who uses arrays on the heap anyways so whatever.
Note: This is relevant to this question as it works with const char * as requested. Works with other types too.
strlen
might be faster because of compiler specific things and regardless it's better to use the code that's already been written for you. – Watereddownstrlen()
? – Wilhelmstrassestd::string
, then you can use itssize()
method. – Watereddownchar
you can talk about the length of that array. Don't muddle pointers and arrays; that leads to endless confusion. – Maisonette