Check if an Int is in an array C/C++
An answer to this question on Stack Overflow.
Question
I am writing a function that takes an int and an array of int as arguments and return true if the int is in the array.
boolean in_array(int subject,int array[]){
int length;
int k;
length = sizeof(array)/sizeof(array[0]);
for(k=0;k<length;k++){
if(array[k]==subject) return true;
}
return false;
}
The function is not working properly because sizeof(array)/sizeof(array[0]) doest not return the length. It seams that sizeof(array) always returns 2 no matter how long is the array.
So how to find the array length to find out if the int is in the array?
Answer
When you pass an array as an argument to a function, the array variable is converted into a pointer to an array.
Therefore, sizeof will not return the number of bytes in the array, it will return the number of bytes in a pointer. You must pass the length of the array as a separate variable or include some kind of termination element (a C-style string, for instance, uses the null character \0 to terminate strings).
I have built a program which demonstrates all of this:
#include <iostream>
#include <typeinfo>
void func(int a[10], int b[]){
std::cout<<"a (inside function): "<<sizeof(a)<<"\n";
std::cout<<"b (inside function): "<<sizeof(b)<<"\n";
std::cout<<"a (inside function type): "<<typeid(a).name()<<std::endl;
std::cout<<"b (inside function type): "<<typeid(b).name()<<std::endl;
}
int main(){
int a[10];
int b[40];
std::cout<<"a (outside function): "<<sizeof(a)<<"\n";
std::cout<<"a (outside function type): "<<typeid(a).name()<<std::endl;
func(a,b);
}
The output is:
a (outside function): 40
a (outside function type): A10_i
a (inside function): 8
b (inside function): 8
a (inside function type): Pi
b (inside function type): Pi
Note that outside of the function, a is an int array of length 10 (A10_i) and the size is known. Inside the function, both a and b are pointers to ints (Pi) and the total size of the arrays are unknown.