Size of Array


I got an array of String.

How can I get size of array of String or int using template ?

Thank you

That depends on WHERE you want to get the size, and where the array is defined. The sizeof() function, on the whole array, will give you the size of the array. Then, sizeof() for the type of object in the array will give you the size of an object. Divide the array size by the object size to get the number of elements.

If you want to do this in a function that is passed the array, you can't.

How can I get size of array of String or int using template ?

Why do you (think you) need to use a template?

I would like a generic method that runs on all types :

namespace utils
      template<typename T>
      int sizeOfArray(const T * arrayPtr)
            return (sizeof(arrayPtr) / sizeof(T));

Won't work, because all pointers are the same size.

Any solution ?

Any solution ?

Not that work for all types.

ok thank you. I will duplicate template method then

Why not store the size in a variable? It will be faster, it will make you a better programmer and you will learn a lot from debugging the code.

Debugging code with sizeof operator is too easy as it almost always is a case of sizeofing a pointer and not the array.

You never, and I mean [u]never[/u], need to use sizeoffor this kind of thing. Nor, should you use it.

:) Good luck whatever you choose to do!

This is a C low level approach, not a OO approach no ?

But I agree to code length of each array in my class and code getters to access each length of each arrays that I have in my sources code... ..even if it is repeatitive. OOP

Ok it's a cool lib to manage Array with accessors that focus on numeric types (float int etc..).

I think I am facing front to a problem of conception.

In fact, I manage a array of struct that contains :

struct {
int      relayNumber  ===> 1
String relayLabel      ===> "Device01"
} t_relay

Hum then a PinManager class got a member that is an array of many relays (5). t_relay embedRelays[MAX_RELAYS_NUM];

Ok. then I have another class "FunctionalTasks" that contains come functions to Trace to LCD and I would like to trace all relays label of PinManager class to the LCD from bottom line to top line.

1/ I think I have to pass embedRelay array from PinManager class to FunctionalTasks class 2/ Putting this in a queue 3/ Then starting a function that empty queue displaying each data on LCD Screen.

Do you think it is a bad way ?

(nb: I am wondering why using a queue now...)