我(认为我)理解,只有在编译时在堆栈上声明数组时,才能使用sizeof检索数组的大小,例如:
int my_array[] = {1,2,3};
sizeof(my_array) == 3;
一旦你开始使用指针,就会失去数组的长度信息。
例如,如果你将一个 int 指针作为函数参数传递,以获取一个 int 数组到函数中,你就不能再像这样使用 sizeof()
,它只会返回用于存储指针的字节数。
显然,知道你的数组有多长非常重要。
那么,在传递数组时我应该使用以下哪个选项呢?
Pass a pointer and an accompanying length parameter
int my_func(int *my_array, size_t len_my_array)
Create my own vector struct
struct vector { int *my_array; size_t len; } int my_func(struct vector *my_vector)
Use someone elses vector implementation. (Is there a default implementation for C as there is for C++?)
Another approach which I've missed?
我目前正在使用第一种选项,但它有些笨重,我很想知道这是否被认为是糟糕的编程实践。