Size of char pointer array from function

2019-01-26 02:47发布

Using this code:

#include <stdio.h>

void printSize(char *messages[]) {
    printf("%d", sizeof(messages) / sizeof(char *));
}

int main(void) {

    printf("Size when through passing direct to function: ");
    printSize((char *[]){"Zero", "One", "Two", "Three"});
    printf("\n");

    printf("Size when calculating in main: %d\n", sizeof((char *[]){"Zero", "One", "Two", "Three"}) / sizeof(char *));

    return 1;
}

I get output:

Size when through passing direct to function: 1
Size when calculating in main: 4

I understand there is no way to get the correct amount of elements in a char* array, but I am curious as to why they are giving different results.

2条回答
ら.Afraid
2楼-- · 2019-01-26 03:09

When you use an array as a parameter to a function, it "decays" to a pointer to the first element of the array. Since messages is an array of pointers to char, when the array is passed to the function, it becomes a pointer to a pointer to a char. This happens even though you are specifying it as an array in your parameter list; that is just how the language works.

So in void printSize(), when you use sizeof(messages), you get the size of a pointer. You are dividing that by the size of another pointer sizeof (char*). On your system, the size of a pointer is 4 bytes in both cases, so the result you get is 4 / 4, i.e., 1.

In main(), however, your array of char* is defined as, and treated as, an array. When the sizeof() operator is applied to an array, you get the size of all the bytes in the entire array. What is this an array of? It's an array of four pointers to char. Each pointer has the size 4. So the total size of the array is 4 * 4 = 16 bytes. You are dividing this 16 by the size of a single pointer to char, which is 4. So you are getting the result 16 / 4, i.e. 4 as the answer in main().

查看更多
beautiful°
3楼-- · 2019-01-26 03:26
  1. It's because char *messages[] is just syntactic sugar for char **messages, so you're just getting the size of a pointer, not the size of your whole array.

  2. You can't, without passing the size along as another parameter.

You should check out the comp.lang.c FAQ section on Arrays & Pointers.

查看更多
登录 后发表回答