Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of static array

Tags:

c++

arrays

size

I declare a static char array, then I pass it to a function. How to get the no. of bytes in the array inside the function?

like image 321
Ron Avatar asked Jan 17 '09 10:01

Ron


1 Answers

Use a function template instead that has a non-type template parameter:

template <size_t N>
void func(char (&a)[N]) {
    for (int i = 0; i < N; ++i) {
        cout << "a[" << i << "] = " << a[i] << endl;   // Or whatever you want to do
    }
}

To call:

char myArray[500];        // Or "static char myArray[500]", if you want
func(myArray);

A new copy of this function will be instantiated for each distinct size of array that it is called with, so if you call it with many different-sized arrays, you'll get some code bloat. But that's not likely to be the case.

like image 95
j_random_hacker Avatar answered Sep 18 '22 11:09

j_random_hacker