Writing a function to search an array for a value and return the index if found. in finding what the size of the array is for use in the while loop condition i found that here inside the templated function sizeof(data) comes back as 4(it should be 40) but when i test the sizeof the array outside of the function it gives me the proper size. neither me nor my teacher are sure why. any ideas?

#include <iostream>

using namespace std;

template<class T1>
int find(const T1 *data,T1 num){
	int i = 0, size = sizeof(data)/sizeof(T1);
	while(i < size){
		if(data[i] == num){return i;}
		else{i++;}
	}
	return -1;
}

int main()
{
int test[10];
test[9] = 1;
test[8] = 2;
test[7] = 3;
test[6] = 4;
test[5] = 5;
test[4] = 6;
test[3] = 7;
test[2] = 8;
test[1] = 9;
test[0] = 10;

int user = 0;
cout << "Please enter the number to search for: ";
cin >> user;
cout << user << " is at index: " << find(test, user) << endl;

	return 0;
}

Recommended Answers

All 4 Replies

I have no problem trying sizeof(test)/sizeof(int) in main but in the template function it outputs 1.

Because passing an array to a function reduces it to just a pointer to the first element, and the size information is lost.

Just like it were a regular function.

You can solve it by doing this instead:

template<class T1, class T2>
int find(const T1 &data, T2 num){

	int i = 0, size = sizeof(data)/sizeof(*data);
	while(i < size){
		if(data[i] == num){return i;}
		else{i++;}
	}
	return -1;
}

This sets T1 to type int[10] and T2 to type int.

When trying to calculate the size of an array use:

int intArray[] = { 1, 2, 3 };
cout << "The size of intArray is: " << sizeof(intArray) / sizeof(intArray[0]);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.