0

Why does this return a length of 8??

#include <stdio.h>

int getLength(char arr[]) {
    return sizeof(arr) / sizeof(arr[0]);
}

char text[] = "1234567890123456789";

int main (void) {
    int i;

    int e=getLength(text);
    printf("%d\n",e);
    for (i = 0; i < e; i++) {

        printf("%c\n", text[i]);
    }

    return 0;
}
Max Leske
  • 5,007
  • 6
  • 42
  • 54
mipesom
  • 13
  • 1
  • 2
    This is asked again and again (the last time that I saw it was 3 hours ago: http://stackoverflow.com/questions/21205730/using-array-in-function-c). A simple Google search "sizeof array wrong" immediately leads to answers. – Martin R Jan 18 '14 at 18:17

2 Answers2

2

because when you pass an array as an argument, it decays to a pointer. So sizeof(arr) yields the size of the pointer (which is 8 bytes on your architecture), not the whole size of the array.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • To add to this, in C you pretty much always want to pass the length of the array to the function handling it. – Enzo Jan 18 '14 at 18:34
  • @Enzo: I was going to write it but then I realized that the aim of the function was to compute the length :) – Jack Jan 18 '14 at 18:53
  • Oh oops! That's true! I'm kind of curious now: if I had allocated an array and forgotten its size, is there anyway in C to figure that out later? – Enzo Jan 19 '14 at 19:46
-2

Because sizeof(array) will give you the size of the array pointer and NOT the actual size of the array itself.

abhi
  • 3,476
  • 5
  • 41
  • 58
  • This is not correct, `sizeof(array)` yields the total byte size of the array if it is not decayed to a pointer. Eg: `char array[10]; sizeof(array)` – Jack Jan 18 '14 at 18:52
  • @Jack I answered it keeping in mind the code he had posted – abhi Jan 18 '14 at 19:02