0

I have tried 2 ways to code length of an array one works the other not and I just don't understand what's the problem. First one works, secon not. This works:

#include<stdio.h>

  int main(void)
  {
    char array[] = {'r', 'o', 'c', 'k', 'n', 'r', 'o', 'l', 'l'};

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

This doesn't work, it always gives me 4.

#include<stdio.h>


unsigned int arraylen(const char *array)
{

    unsigned int length = sizeof(array) / sizeof(array[0]);
    return length;
}

int main(void)
{
    const char array[] = {'r', 'o', 'c', 'k', 'n', 'r', 'o', 'l', 'l'};
    unsigned int length = arraylen(array);
    printf("Length is %d\n", length);

    return 0;
}
  • As described (very nicely) in the answers in the linked question, your function receives *only a plain pointer* and that is of fixed size. In `main` the variable is an array whose actual number of elements is known to the compiler. – Adrian Mole Jun 20 '20 at 16:49

1 Answers1

1

The reason why the second one doesn't work is because the array is being passed into the arraylen function as a pointer. In C, a pointer just points to the beginning of your array and knows nothing about the length of the array.

So essentially, in the second one, you are taking the sizeof(pointer to array)/sizeof(array[0]). The size of a pointer is always the same (but varies across machines) so this is why you always get 4.

In contrast an array's size is what you would think i.e. sizeof(each element) * number of elements. That's why the first one works.

eracer9
  • 80
  • 1
  • 10
  • Thank you for your answer. Would you be willing to tip me how can I return the correct value from my function? I'm kind of desperate at the moment. I'm a novice as you probably guessed. – stadironin Jun 20 '20 at 17:01
  • There is no way to do that inside a function. See this answer: https://stackoverflow.com/questions/17590226/finding-length-of-array-inside-a-function – eracer9 Jun 20 '20 at 17:17
  • Tyvm. I used strlen() and it worked perfectly :) – stadironin Jun 20 '20 at 17:32