Array by reference length in C++ -


possible duplicate: calculating size of array

this question has been asked before, want confirm it. let's have following c++ function:

#include <stdio.h> #include <stdin.h> #define length(a) sizeof(a)/sizeof(a[0])  int main() {     double c[] = {1.0, 2.0, 3.0};     printf("%d\n", getlength(c));     return 0; }  int getlength(double c[]) { return length(c);} 

this should return wrong value because size of return size of pointer opposed size of array being pointed at. this:

template<typename t, int size> int length(t(&)[size]){return size;} 

i know works directly, want know if can somehow call indirectly i.e. via helper function. understand 2 possible alternatives either store length of array in separate slot or use vector, want know is:

given function getlength:

getlength(double arr[]) { ... } 

is there way compute length of arr without passing more information?

the template version work. said not work?

template<typename t, int size> int length(t(&)[size]) {    return size; } 

this correct. return length of array. you need call function directly. seems want call function getlength(). don't that, because way you've written getlength function equivalent this:

int getlength(double *c) { return length(c);} 

there absolutely no difference between written getlength() , above version. is, once call function, (or function), array decayed pointer double. you've lost size information decay of array (which why called decaying of array). should not call function, instead call length() function directly..

however, there little problem length() well. cannot use function const-expression needed, such:

int anotherarray[length(c) * 10]; //error 

so solution this:

template < std::size_t n > struct value2type { typedef char type[n]; };  template < typename t, std::size_t size > typename value2type<size>::type& sizeof_array_helper(t(&)[size]);  #define length(a) sizeof(sizeof_array_helper(a)) 

now can write:

int anotherarray[length(c) * 10]; //ok 

Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -