Reputation: 11
I want to use sizeof
operator after passing an array to a function but C language is considering it as pointer not an array.
Can we implement a functionality to solve this purpose ?
void foo(char array[])
{
printf("sizeof array = %u\n", sizeof(array)); /* I know array is pointer here */
}
int main(void)
{
int array[5];
foo(array);
}
Upvotes: 1
Views: 113
Reputation: 4454
You can't ask the compiler for that. It is not polite to do what you ask it to.
Instead you can add another parameter to your function definition to recieve the size of the array.
void foo(char array[], size_t array_size)
{
printf("sizeof array = %zu\n", array_size);
}
int main(void)
{
int array[5];
foo(array, sizeof(array)) ;
}
Note: to print size_t use %zu in printf.
Note: to print number of elements, use: sizeof(array) / sizeof(*array)
Upvotes: 1
Reputation: 2953
Not possible and using an array subscript []
can be confusing to people not knowing that it will behave as a pointer. The approach that I take is to pass length as another argument or create a struct with pointer and length:
struct {
char * buffer;
size_t length;
} buffer_t;
I don't like the array in the struct or typedef approach as it restricts the data to a fixed size.
Upvotes: 1
Reputation: 32596
You can use a dedicated typedef, or as said in a remark an embedding struct :
#include <stdio.h>
typedef char A5[5];
typedef struct S {
char a[5];
} S;
void foo(A5 a) /* of course can be "void foo(char a[])" but less clear */
{
printf("%zu %zu\n", sizeof(A5), sizeof(a));
}
void bar(S s)
{
printf("%zu\n", sizeof(s.a));
}
int main()
{
A5 a;
S s;
foo(a);
bar(s);
}
Of course in case of the typedef you need to use typeof on it rather than on the var being a char*
But all of that is a kind of hack, C is C ...
Upvotes: 0