system
Given the following post, respond as if you're commenting on Reddit:
human
Question involving use of sizeof() to get the size of an array in C

Hello; sorry if this is a silly question, but I don't get why sizeof(ptrtoArr) returns 8 (instead of 7?) within the binsearch() function I'm creating.

    #include <stdio.h>
    
    // Linear search
    void linsearch(int *ptrtoArr, int target){
        for (int i = 0; i < sizeof(ptrtoArr); i++){
            if (ptrtoArr[i] == target){
            printf("Target is element #%d.\n", i+1);
            }
        }
    }
    
    // Binary Search
    void binsearch(int *ptrtoArr, int target){
        int size = sizeof(ptrtoArr);
        printf("The size of this array is %d.\n", size); //why 8?
        
    }
    
    
    int main(){
        int array[7] = {-2, 3, 4, 7, 9, 11, 13};
        int target = 11;
        linsearch(array, target);
        binsearch(array, target);
        return 0;
    }

Edit: Ok thanks everyone! Haven't read through everything in detail yet, but I'll just pass the array size for now.
gpt
Sizeof() probably doesnt work the way you think, it will not even give 7 as correct result, but 28. Sizeof returns size of the array in bytes and since you have 7 integers with 4 bytes each, this snippet

    int array[7] = {-2, 3, 4, 7, 9, 11, 13};
    printf("%d", sizeof(array));

Will print 7 \* 4 bytes = 28. You can often get the correct number by dividing by size of integer:

    int array[7] = {-2, 3, 4, 7, 9, 11, 13};
    printf("%d", sizeof(array) / sizeof(int));  // prints 7

So why is it 8 then?

When you pass the array to a function, you cast the array from `int[7]` to `int *`. This is called "array decay" and you lose the information about the size of the array. The result 8 you see is actually size of int \*.

    printf("%d", sizeof(int *));  // prints 8

This is why so many functions that work with arrays use extra argument where you provide the length of the array, because you can not work out the size after the array has decayed to just a pointer.

Edit: That also means that the first function is wrong, even if it may work. Since the upper limit in the for loop is 8, the biggest index you access is 7, which is not valid in the array.