All of them are functionally identical. When you pass an array to a function in C, the array gets an implicit conversion to a pointer to the first element of the array. Therefore, these three functions will print the same result (i.e. the size of the char pointer).
void func1(char* str) { printf("sizeof str: %zu\n", sizeof str); } void func2(char str[]) { printf("sizeof str: %zu\n", sizeof str); } void func3(char str[10]) { printf("sizeof str: %zu\n", sizeof str); }
This conversion applies only to the first size of the array. A char[42][13] converted to char (*)[13] , not char ** .
void func4(char (*str_array)[13]) { printf("sizeof str_array: %zu\n" "sizeof str_array[0]: %zu\n", sizeof str_array, sizeof str_array[0]); }
char (*)[13] - type str_array . This is how you write "pointer to an array of 13 char s". It could also be written as void func4(char str_array[42][13]) { ... } , although 42 is functionally pointless, as you can see by experimenting by passing arrays of different sizes to func4 .
In C99 and C11 (but not C89 or C ++), you can pass a pointer to an array of different sizes in a function by passing its size with it and including the size identifier in [square brackets] . For example:
void func5(size_t size, char (*str_array)[size]) { printf("sizeof str_array: %zu\n" "sizeof str_array[0]: %zu\n", sizeof str_array, sizeof str_array[0]); }
This declares a pointer to an array of size char s. Note that you must dereference the pointer before accessing the array. In the above example, sizeof str_array[0] evaluates the size of the array, not the size of the first element. As an example, to access the 11th element, use (*str_array)[11] or str_array[0][11] .
Sebivor Apr 22 '13 at 10:50 2013-04-22 10:50
source share