im trying to create a function that will execute a for loop as many times as the size of array which contains pointers to structobjects.
the only thing i can send to the function its a pointer to the beginning of the array.
I recommend to use std::array<> and just call .size() member function and it will return the number of elements inside it :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <array>
struct Student
{
unsigned id;
// ...
};
int main()
{
using std::array;
array<Student, 10> student;
for ( size_t i = 0; i < student.size(); ++i ) {
student[ i ].id = i;
}
}
unfortunately, afaik, there is no way to know the size of the array by only passing a pointer to the beginning of the array.
You must use some form of syntactic sugar and template deduction technique :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
struct Student
{
unsigned id;
}
// can work with any type of array (char, float, double, etc...)
template <typename T, size_t N>
constexpr size_t length ( T (&)[ N ] ) // C++11 (constexpr so that this function is called at compile-ime
{ return N; }
int main()
{
Student student[ 50 ];
for ( size_t i = 0; i < length(student); ++i ) {
student[ i ].id = i;
}
NOTE you must enable c++11 mode in ur compiler to use std::array<> and constexpr, -std=c++11 or -std=c++0x on GCC