我有这个代码:
#include <stdio.h>
void sample(int b[3])
{
//access the elements present in a[counter].
for(int i=0;i<3;i++)
printf("elements of a array are%d\n",b[i]);
}
int main()
{
int count =3;
int a[count];
int i;
for(i=0;i<count;i++)
{
a[i]=4;
}
for(i=0;i<count;i++)
{
printf("array has %d\n",a[i]);
}
sample(//pass the array a[count]);
}
我想在 main()
之外的用户定义函数中访问在这个 main 函数中声明的数组,方法是将它作为此函数的参数传递。我该怎么做?
最佳答案
期望它的函数通常必须知道数组的位置和它的大小。为此,您需要将指针传递给数组的第一个元素。
您的示例函数可能看起来像
void sample(int *b, size_t count) {
for(int i = 0; i < count; i++) {
printf("elements of a array are%d\n",b[i]);
}
}
您可以通过传递指向其第一个元素的指针来“传递”数组,当然,还可以传递数组的长度。
sample(a, count);
如果您可以确定数组至少有 3 个元素长,您也可以通过省略计数参数来简化此过程。
关于c - 访问函数中 main 中存在的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19558370/