There are two issues in your code:
- You are accessing a memory address which you have not reserved:
array[n]
- Within
ifInList
you intend to use the name n
for both the size of the array (your global variable) and the value you are looking for.
In particular:
Accessing a memory address you do not own
In this line:
printf("The number is %d \n", ifInList(&array[n], 1));
You are passing &array[n]
as an argument to ifInList
. This introduces two types of errors:
- Addressing error:
array[n]
does not exist. It refers to the n+1
-th element of the array, a memory address which you have not reserved. In other words, you are "out of bounds".
- Logical error: you are not passing the address of the first element of the array. If you fixed it to, say,
array[n-1]
, your function will only look at the last element of your array. In order to start searching from the first element, you need to pass either array
or &array[0]
; both are identical and refer to the memory address of the first element.
Conflicting variable names
First things first: global variables are almost always a bad idea, they should only be used in "quick and dirty" programs and/or for quick debugging purposes, as they can introduce confusion.
You are defining n
as a global variable, which refers to the size of array
. Nevertheless, within function ifInList
, variable n
has a different meaning: it's the key you are looking for. Therefore, if you are looking for "42" in a array
with 3 elements, your function will look up to 42 different elements, instead of 3!
To avoid this confusion, give a different name to the key you are looking for:
int ifInList(int array[], int k){
for (j = 0; j < n; j++){
if (array[j] == k){
return 1;
}
}
return 0;
}
And the recommended approach is to provide the size with the key as arguments, thus eliminating completely the need for a global variable and any other potential conflicts. Furthermore, it's a clean programming practice. Note how I am also defining j
within the function:
int ifInList(int array[], int n, int k){
int j;
for (j = 0; j < n; j++){
if (array[j] == k){
return 1;
}
}
return 0;
}