Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ syntax pointer for array

In the following:

int c[10] = {1,2,3,4,5,6,7,8,9,0};

printArray(c, 10);

template< typename T >
void printArray(const T * const array, int count)
{
    for(int i=0; i< count; i++)
        cout << array[i] << " ";
}

I am a little confused why the function signature of the template function makes no reference to array being an array by using [], so something like const T * const[] array.

How could one tell from the template function signature that an array is being passed and not just a non-array variable??

like image 321
user997112 Avatar asked Jul 24 '26 00:07

user997112


1 Answers

You cannot tell for sure. You would have to read the documentation and/or figure it out from the names of the function parameters. But since you are dealing with fixed sized arrays, you could have coded it like this:

#include  <cstddef> // for std::size_t

template< typename T, std::size_t N >
void printArray(const T (&array)[N])
{
    for(std::size_t i=0; i< N; i++)
        cout << array[i] << " ";
}

int main()
{
  int c[] = {1,2,3,4,5,6,7,8,9,0}; // size is inferred from initializer list
  printArray(c);
}
like image 171
juanchopanza Avatar answered Jul 26 '26 13:07

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!