0

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?

Ihidan
  • 558
  • 1
  • 7
  • 25
  • 1
    `sizeof(array)` is not doing what you think it does. You'll need to pass the size of the array to the function or use a container like `std::array` or `std::vector`. See [Sizeof array passed as parameter](http://stackoverflow.com/questions/1328223/sizeof-array-passed-as-parameter). – Captain Obvlious Sep 03 '15 at 02:15
  • I can't use containers so I guess the only option is to pass the size along it. – Ihidan Sep 03 '15 at 02:16
  • @Ihidan Actually no, you can pass arrays in a way that preserves their dimension, namely by reference or via pointer to array. Read the top answer of the dupe. – Baum mit Augen Sep 03 '15 at 02:19
  • Pick a language. C++ has `std::find`, C does not. – MSalters Sep 03 '15 at 08:30

1 Answers1

0

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.

Richard
  • 56,349
  • 34
  • 180
  • 251