传递数组大小以及c中的指针 [英] Passing Array Size along with pointer in c
本文介绍了传递数组大小以及c中的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数 foo
,该函数处理用户定义大小的数组的元素.
I have a function foo
which processes the elements of an array whose size is user defined.
此函数需要两个参数(不一定是两个单独的参数,或者我认为也是如此)-指向数组和数组大小的指针.
This function needs two parameters (not necessarily two separate arguments, or so do I think) - a pointer to the array and size of the array.
以下用于调用该函数的三种方法有效吗?
Are the three methods used below to the call the function valid?
int size; // Obtained from user
int arr[size];
foo(int (*arr)[size]); // Will size be available as a vairable inside foo ?
foo(int (*arr)[],size);
foo(int (*arr)[size],size); // Is the 2nd parameter redundant here ?
推荐答案
在C中,大小不是数组对象"的一部分.因此,惯用的C代码将数组的大小与数组本身一起传递:
In C, the size is not part of the array "object". Therefore, idiomatic C code passes the size of an array along with the array itself:
foo(arr, size);
功能
void foo(int arr[], int size);
(对于整数数组).
例如参见 main
函数:
int main(int argc, char *argv[]);
(请注意,这里的参数是相反的.)
(Note the arguments are reversed here.)
这篇关于传递数组大小以及c中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文