-2

I am trying to find the smallest missing element of an array using function check, which has two arguments (n and array A). I can't understand why my function check is always returning one and the while loop is never closing.

#include <stdio.h>

bool check(int n, int A[])
{
    for (int i = 0; i < sizeof(A); i++)
    {
        if(A[i] == n) 
        {
            return 1;
        }
    }
    return 0;
}

int main()
{
    int A[] = {1, 3, 6, 4, 1, 2};
    int n = 1;

    while (check(n, A) == 1)
    {
        n++;
    }
        
    printf("%d is missing",n);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Louis
  • 19
  • 5
  • 2
    `sizeof(A)` (in the function) doesn't do what you think it does. Looking for a dup... [Why sizeof(param_array) is the size of pointer?](https://stackoverflow.com/questions/11622146/why-sizeofparam-array-is-the-size-of-pointer) – Weather Vane May 13 '22 at 19:01
  • 1
    I know but still that's not why the while loop is never stopping. – Louis May 13 '22 at 19:06
  • 1
    Ah. Add `\n` to the print and see if that solves it. – hyde May 13 '22 at 19:08
  • If that doesn't solve it, debug your code: add debug print inside the loops. – hyde May 13 '22 at 19:09
  • 2
    Having corrected that error, cannot replicate. The loop ends, and the message is printed, the program ends. It's no use saying "I know my program has an error but that isn't the reason". – Weather Vane May 13 '22 at 19:11

1 Answers1

2

The compiler adjusts a parameter having an array type to pointer to the array element type.

So this function declaration

bool check(int n, int A[])

is equivalent to

bool check(int n, int *A );

And within the function the expression sizeof(A) is equivalent to the expression sizeof( int * ) and is equal to either 4 or 8 depending on the used system.

Thus this for loop

for (int i = 0; i < sizeof(A); i++)

invokes undefined behavior.

I know but still that's not why the while loop is never stopping.

Answering your above comment it seems that in the used system sizeof( int * ) is equal to 8 and the variable n is placed in memory after the array A as they defined in main

int A[] = {1, 3, 6, 4, 1, 2};
int n = 1;

As a result you get the infinite wile loop because in the for loop within the function the memory occupied by the variable n is checked and n is always equal to itself.

Thus the function always returns 1.

That is in the for loop the array is traversed as it has 8 elements like

int A[] = {1, 3, 6, 4, 1, 2, n, some_indeterminate_value };
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335