c - 传递一维数组、二维数组和指针数组

标签 c arrays pointers

要将一维数组传递给函数,我们这样做:

#include <stdio.h>
#include <stdlib.h>

void func(int *arr, int n)
{
    // code here

}

int main()
{
    int arr[] = {......};                   // declare array
    int n = sizeof(arr)/sizeof(arr[0]);
    func(arr);                              // calling function func

    return 0;
}

要将二维数组传递给函数,我们这样做:

#include <stdio.h>
#include <stdlib.h>

void func(int arr[][2])
{
    // code here
    }

int main()
{
    int arr[3][2];  // declare 2D array
    func(arr);      // calling function func

    return 0;
}

那么在将指针数组传递给函数时,我们可以这样做吗?

#include <stdio.h>
#include <stdlib.h>

void func(int **arr, int n)
{
    // code here

}

int main()
{
    int *arr[] = {......};                // declare array of pointers
    int n = sizeof(arr)/sizeof(arr[0]);
    func(arr, n);                           // calling function func

    return 0;
}

老实说,我对指针和数组感到困惑。我花了很长时间才弄清楚如何传递二维数组。我尝试搜索其他类似的问题,但没有成功。请帮助我:将指针数组传递给函数。另外,任何可以消除困惑的链接都将非常感激。

最佳答案

在上一个示例中,您有一个指针数组

是的,那会起作用,例如检查这个玩具示例:

#include <stdio.h>
#include <stdlib.h>

void func(int **arr, int n) {

    // print equal to arr[0][1] 
    printf("%d %d\n", n, *arr[1]);
}

int main(void) {
    int a = 1, b = 2, c = 3;

    // set the points of a, b, and c, to arr[0][0..2];
    int *arr[] = {&a, &b, &c};
    int n = sizeof(arr)/sizeof(arr[0]);
    printf("%d %d\n", n, *arr[1]);

    func(arr, n);

    return 0;
}

输出:

3 2
3 2

关于c - 传递一维数组、二维数组和指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51168890/

相关文章:

c++ - 使用常量变量声明对象数组

c++ - C++/链表中的指针

arrays - 快速查找字符串数组之间的匹配项

c - 从C中的字符串中删除出现的数组

c - C中的gets()函数会自动在输入字符串的末尾添加一个NULL字符吗?

c - 函数错误 'expected expression before char'?

C++: Address-of dereference 和 dereference of an address-of

动态创建二维数组并复制txt文件。分割错误

c - Kernighan 和 Ritchie 的 "C Programming Language"第二版的良好后续

c - "error: expected ' ; ', ' , ' or ' ) ' before numeric constant"即将出现在我的代码中