gpt4 book ai didi

c - 将二维数组传递给函数时,单指针和双指针有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 16:06:40 28 4
gpt4 key购买 nike

我们可以将二维数组作为单指针和双指针传递。但在第二种情况下,输出不符合预期。那么第二段代码有什么问题呢?

方法一:

#include <stdio.h>
void print(int *arr, int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", *((arr+i*n) + j));
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3, n = 3;
print((int *)arr, m, n);
return 0;
}

输出:

1 2 3 4 5 6 7 8 9

方法二:

#include <stdio.h>
void print(int *arr[], int m, int n)
{
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
printf("%d ", *((arr+i*n) + j));
}

int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int m = 3;
int n = 3;
print((int **)arr, m, n);
return 0;
}

输出:

1 3 5 7 9 3 0 -1990071075 0

最佳答案

第一个是未定义的行为:Accesing a 2D array using a single pointer .

第二个完全错误,您不能将二维数组 (arr[][3]) 传递给 int 指针数组 ( *arr[]), 查看Correct way of passing 2 dimensional array into a function :

void print(int *arr[], int m, int n)

必须是

void print(int arr[][3], int n) /* You don't need the last dimesion */

void print(int (*arr)[3], int n) /* A pointer to an array of integers */

But this way the column in arr[][3] must be globally defined. Isn't any other workaround?

在 C99 下,您可以使用 VLA(可变长度数组):

void print(int rows, int cols, int arr[rows][cols])

关于c - 将二维数组传递给函数时,单指针和双指针有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28691213/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com