0

I have a question about getting the length of an array in C. I always get the result 1. This result probably comes from the fact, that int is 4 bytes big, and 4 / 4 = 1. So the problem is that I dont get the size of the whole array, only of a single value in it.

Here is my code:

#include <stdio.h>

int getArrayLength(int array[]);

int main()
{
    int myArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    printf("Length of array is: %d", getArrayLength(myArray));

    return 0;
}

int getArrayLength(int array[])
{
    int size = (int) sizeof(*array) / sizeof(array[0]);
    return size;
}

Maybe someone can help me fixing my problem.

Thank you^^

Flo487
  • 11
  • 1
  • If you make getArrayLength a function, then `array` is a variable in a different scope. It's not possible to get the array size in that function. You should probably make it a preprocessor macro. – Cheatah May 01 '21 at 10:27
  • TL;DR for the suggested duplicate (there may be a better one): An array passed as a function argument decays to a pointer. – Adrian Mole May 01 '21 at 10:28
  • Also, can you explain what you think `sizeof(*array)` is and why you would need to divide it by `array[0]`? – Cheatah May 01 '21 at 10:28
  • @Cheatah i think he is trying to get byte size of the whole array and divide by the byte value of each position, but yeah, that don't work that way, actually ```*array``` and ```array[0]``` are the same that's why the result its always 1 – Paul Bob May 01 '21 at 10:30
  • Yeah, it did^^ Thank you – Flo487 May 01 '21 at 10:37
  • @Cheatah Well, I know that the pointer just points to a single value of the array. Thats why I got 4. But my actual question was, how I can get the size of the full size of the array. But I have already fixed the problem. Thank you^^ – Flo487 May 01 '21 at 10:40

0 Answers0