user2904478
user2904478

Reputation: 27

C++ generic template

Hello all i am just beginning to learn c++ and just looked at templates. I was asked to make a template function print that would take an array and a int input and print out the elements in the array. Here is my code.

#include <iostream>
using namespace std;

template <typename T>
void print(T a[], int b)
{
     for(int y=0; y < b; y++)
     {
        cout << a[y] <<" ";
     }

}

int main()
{

int arr[5];
int size = sizeof(arr);

for(int h=0; h<=size; h++)
{
    arr[h]=0;
}

print(arr,size);

}

The program compiles with no errors but when I run it there is no output. Can anyone help? or point me in the right direction?

Upvotes: 0

Views: 92

Answers (2)

David G
David G

Reputation: 96810

Your program has Undefined Behavior at this point:

for (int h = 0; h <= size; h++)
{
    arr[h] = 0;
}

You defined size to be the number of bytes held in the array arr, not the actual number of integers present. Therefore, an integer on your platform is most likely greater than 1 byte, so size will be equal to a number far greater than 5.

And when you do arr[h], you're eventually going to access an address beyond the bounds of the array. It is at that point that your program contracts a case of Undefined Behavior. At that moment, anything in your program can happen, including the output not appearing.

The fix to this problem is to divide the bytes present in arr by the size in bytes of a single int. That will tell you the number of elements:

int size = sizeof(arr)/sizeof(int);

An even better solution is to use std::array so that the size is known and can be accessed through its member function size:

std::array<int, 5> arr{{}};

for (int i = 0; i < arr.size(); ++i)
    arr[i] = 0;

Note that using aggregate-initialization on std::array causes zero-initialization of each element. Thus, there is no use for the subsequent for loop.

You'll also need to adapt your function so that it can access an array object:

template<typename T, unsigned N>
void print(const std::array<T, N>& a)
{
    for (const auto& x : a) // range-based for loop
    {
        std::cout << x;
    }
}

Upvotes: 2

john
john

Reputation: 87959

The error is in the value of the variable size.

int size = sizeof(arr);

gives the size of the array in bytes, it is not 5.

int size = sizeof(arr)/sizeof(arr[0]);

will give the right answer.

It would also be a good idea to add

cout << endl;

at the end of main.

Upvotes: 1

Related Questions