sizeof operator

The printf function below prints 16 bytes for the size of test. Now test is an array of char pointers. I believe the size of a pointer is by default 4 bytes. Since the array has four char** pointers, its size is 12 bytes. But what is a little confusing is the variable "test". Isn't that only pointing to the first char pointer? And therefore shouldn't it only be printing 4, since by default arrays point to their first elements?

1
2
  char *test[] = {"Foo", "bar", "0x10", "0x2A"};
  printf("The size of test: %d", sizeof test);

btw the format specifier for printing output from sizeof operator is %zd. In regards to your question, you are calculating the size of test aka char **. This value is determined at runtime because the compiler knows the number of elements in the array and is therefore able to calculate this value.

If you want to see the value 4, then get the size of the first element in the array by doing:

printf("The size of the first element in array 'test' is : %zd", sizeof *test);

In the case that you have dynamically allocated memory for this array, the compiler will not have a way of determining the size of the dynamic array until during runtime. Here it will use the values supplied to either malloc function or the new operator to determine the size in bytes of the object
Last edited on
I believe the size of a pointer is by default 4 bytes

The size of a pointer is implementation defined. There is no default.

But what is a little confusing is the variable "test". Isn't that only pointing to the first char pointer? And therefore shouldn't it only be printing 4, since by default arrays point to their first elements?

No. Arrays consist of the stored elements. test has type char*[4]. The name may be implicitly converted to a pointer to the first element, but there is no such conversion here.
Topic archived. No new replies allowed.