Rivf
Rivf

Reputation: 125

Get Array Length using Templates (Assignment)

I am trying to write a code that gets the length of an array with any type. I can't change anything in the main function since this is an assignment. The code I wrote is the implementation of array_length. I do not understand why I can get the length of both the int and the double but not the length of the char array. I am assuming that it has to do something with the fact that int and double's 0 is just zero. It means, the value is zero. But char '0' is not zero. '0' is an ASCII code, so '0' has a value 48 or 0x30. I am not sure though. I appreciate any help.

Here is my entire code:

#include <iostream>
using namespace std;

template<class T, size_t N>
    T array_length(T (&arr)[N]){

    
    T length = sizeof(arr)/sizeof(T);
    
    return length;
}

int main()
{
    int a[6]={2,7,4,2,2,0}; char b[8]="GEBD030";
    double c[7]={4.5, 4.0, 3.5, 3.0, 2.5, 2.0, 0.0};
    cout << "a:" << array_length(a) << endl;
    cout << "b:" << array_length(b) << endl;
    cout << "c:" << array_length(c) << endl;
    return 0;
}

Upvotes: 1

Views: 115

Answers (1)

songyuanyao
songyuanyao

Reputation: 172894

The return type of array_length is T, when being passed a char array, the return type would be char. Then std::out would print the return value as a char with ASCII code 8.

Change the return type to std::size_t.

template<class T, size_t N>
size_t array_length(T (&arr)[N]){
    ...
}

BTW: As the implementation, you can just return the template parameter N. e.g.

template<class T, size_t N>
size_t array_length(T (&arr)[N]){
    return N;
}

Upvotes: 4

Related Questions