传递数组在C参数 [英] Passing arrays as parameters in C
问题描述
我(我想)明白,如果它是在堆栈中,例如在编译时声明,你只能检索(使用的sizeof)数组的大小。
I (think I) understand that you can only retrieve the size of an array (using sizeof) if it is declared at compile time on the stack, e.g.
int my_array[] = {1,2,3};
sizeof(my_array) == 3;
一旦你开始使用指针,你失去了这个长度的信息。
As soon as you start using pointers you lose this length information.
例如。如果你传递一个指针为int作为函数参数来获得一个int数组,你可以不再使用功能的sizeof()
这样,它只是返回的数量的字节用于存储指针。
e.g. if you pass a pointer to int as a function parameter to get an int array into a function you can no longer use sizeof()
in this way, it will just return the number of bytes used to store a pointer.
显然,这是至关重要的知道你的数组有多长。
Clearly, it is vital to know how long your arrays are.
那么,哪下列选项绕过阵列时,我应该使用?
So which of the following options should I use when passing arrays around?
-
传递一个指针和一个伴随的长度参数
Pass a pointer and an accompanying length parameter
INT my_func,并将为(int * my_array,为size_t len_my_array)
创建我自己的矢量结构
struct vector {
int *my_array;
size_t len;
}
int my_func(struct vector *my_vector)
使用别人的载体实现。 (是否有对C的默认实现,因为是C ++?)
Use someone elses vector implementation. (Is there a default implementation for C as there is for C++?)
我已经错过了另一种方式?
Another approach which I've missed?
(我目前使用的第一个选项,但它是一个有点笨拙,我渴望知道,如果这被认为是编程习惯差)
(I'm currently using the 1st option but its a bit unwieldy and I'm keen to know if this is considered poor programming practice)
推荐答案
标准的方法是使用第一种方法并传递一个指针,特别是如果你希望你的code被别人重用的大小。
The standard way is to utilize the first approach and pass a pointer and a size especially if you want your code to be reused by others.
这篇关于传递数组在C参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!