0

When I run the following program, I get different array sizes. I tired different ways but the result is the same, what could io be doing wrong ?

#include<stdio.h>

void array_size(char *a[])
{
    printf("Func Array Size: %d\n", sizeof(a));
}

int main()
{
    char *str_array[]={"one", "two", "three"};

    printf("Array Size: %d\n", (int)sizeof(str_array));

    array_size(str_array);

    return 0;
}
Me Unagi
  • 397
  • 1
  • 6
  • 16

2 Answers2

1

In function main str_array is an array with three char *.

The parameter a of function array_size is just a pointer. The compiler does not dynamically pass array length information when calling array_size.

The size of one pointer is not equal the size of three char * pointers.

Werner Henze
  • 15,667
  • 12
  • 43
  • 65
-1

This is because sizeof is a compiler built-in and not a runtime function. It is hard-coded into the binary.

`sizeof((char *)[]) = sizeof(a) = sizeof(void *)`
`sizeof(str_array) = sizeof({"one", "two", "three"}) = 3 * sizeof(char *)`
Sergey L.
  • 21,074
  • 4
  • 47
  • 69