c - 访问函数中 main 中存在的数组

标签 c

我有这个代码:

#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/

相关文章:

c - 使用 select() 在现有客户端或新客户端之间进行选择 (C)

c - 第一次使用 Malloc,程序崩溃

c - 为什么 128 在一和二的补码中使用 8 位溢出?

代码未运行但编译?

c - 链表的打印功能如何工作?

c - sqlite3编程在Linux C中得到 "out of memory"

c - 将元素插入链表时出现段错误(核心转储)

c - 我从日志中收到一条消息,上面写着 : Error: request for member "height" in something not a structure or union

c - 如何测试数字是否存在科学记数法?

Android Studio CMakeLists错误: undefined reference to