0

so I'm having a little bit of difficulty using sizeof() to determine the length of an array. For clarity, here is my code:

int main(){

  char array[] = "Cats";

  printf("The size of this array is: %i",sizeof(array));

}

And rightly so, this outputs

The size of this array is: 5

My problem starts when I try to use the sizeof operator within a function, and then call that function from main. Like this:

void thefunct(char string[]){

   printf("%i",sizeof(string));

}

and the call in main:

int main(){

   thefunct("Cats");


}

In this case, this outputs 4, which is the size in bytes of the pointer for a character array. So basically, my question is: Why does it produce a '5' when I use sizeof directly in main(), but a '4' when I'm calling it from a separate function?

All answers are appreciated :)

  • Look up any question on why the size-of on pointers doesn't work outside the calling function, and why you always need to pass size as a parameter. – Happington Jun 27 '14 at 18:08
  • 1
    C arrays contain no size indication internally. All the compiler knows is what's declared, and in the case of your function that's an empty array. – Hot Licks Jun 27 '14 at 18:08
  • Mostly relevant to C: [arrays](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) – chris Jun 27 '14 at 18:09
  • 1
    @HotLicks Not an empty array : in a function declaration this syntax decays to a pointer. – Quentin Jun 27 '14 at 18:09
  • @Quentin - Yeah, and you end up taking the length of the pointer. – Hot Licks Jun 27 '14 at 18:12
  • inside the function when you are using sizeof() operator to determine the size of array, you are passing the pointer and it is printing the size of (char *) actually, which is 4 in your compiler's case. – Yatendra Rathore Jul 29 '17 at 11:59

0 Answers0