0

I want the output to be 6 and 4 four array A and B but I cant figure out where I made a mistake. I read a tutorial on StackOverflow where u can calculate a int array length by doing length = sizeof(array)/sizeof(array[0]), but it just doesn't work in my program. The values of sizeof(array) and sizeof(array[0]) stay constant regardless if I change the array as shown below.

#include<stdio.h>
#include<string.h>

int arraychecker(int array[])
{

    int Length =sizeof(array)/sizeof(array[0]);
    int arraylength = sizeof(array);
    int arraylength0 = sizeof(array[0]);
    
    printf("%d,%d,%d\n", Length, arraylength, arraylength0);
    
}

int main()
{
    int a[]= {2,1,3,4,9,33};
    int b[]={2,55,3,2};
    arraychecker(a);
    arraychecker(b);
    
    return(0);
}

output: 2,8,4 2,8,4

Josh
  • 1
  • 2
  • You can't find the length in the function, because arrays decay into pointers when passed to functions and lose the length information. You need to pass the length as extra parameter. – Eugene Sh. Nov 25 '21 at 17:55

1 Answers1

-1

Adding to Eugene's comment, some common practice is to also store the length in the array.

  • 2
    Don't use answers to work around the limitation on posting comments. If it's not a complete answer, it should not be posted as one. Beyond that, storing the length within the array is not at all a "common practice", and at best only works when the array is of a type appropriate to store the length. – ShadowRanger Nov 25 '21 at 17:58
  • Yes i noticed, i fixed the problem already by calculating the length in the main function directly. Thanks for the answer! – Josh Nov 26 '21 at 07:37