c - 将二维数组传递给函数

标签 c arrays pointers multidimensional-array

以下代码部分有效。请帮忙找出错误

#include<stdio.h>
#include<stdlib.h>
void show ( int ( *q )[4], int row, int col )
{
  int i, j ;
  for ( i = 0 ; i < row ; i++ )
  {
    q=q+i;
    for ( j = 0 ; j < col ; j++ )
        printf ( "%d ", * ( *q + j ) ) ;
    printf ( "\n" ) ;
  }
  printf ( "\n" ) ;
}

int main( )
{
 int a[3][4] = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 0, 1, 6}
              } ;
 show ( a, 3, 4 ) ;
 return 0;
}

我只能打印前两个子数组。对于第三个(最后一个)子数组,我得到垃圾值

其他问题

在上面的代码中-

 show ( a, 3, 4 ) ; Through this statement I am passing 'a'. In this case 'a' contains the address of first subarray a[0]. This a[0] address in stored in (*q)[4].

 In show() since q contains a[0] address i am looping through and printing all elements in first sub array (i.e) 1,2,3,4

 In show() again using statement q++, the value of q is changed to point to a[1] (i.e) second sub-array. Then through looping all the elements in 2nd subarray are printed. This process continues.

这里'a'的二维数组名存放'a[0]'首子数组地址。

a[0]第一个子数组存放第一个元素a[0][0]地址等。

问题:

  1. 当我的二维数组被创建时,空间被分配给这些 'a','a[0]','a[1]','a[2]','a[3]' Is'不是吗??除了空间分配给a[0][0],a[0][1],a[1][0]......a[3][4]

  2. 为什么我无法检索“a”和“a[0]”、“a[1]”、“a[2]”、“a[3]”的地址。每当 & 与它们关联时,我都会得到 a[0][0]、a[1][0]、a[2][0] 的地址

最佳答案

错误在这里:

q=q+i;

这首先将 q 增加 0,然后增加 1,然后增加 2,导致它错过第三个元素并直接跳到第四个(在你的情况下,这个索引超过了数组的末尾,给出了垃圾值) .

每次 q++; 都需要递增 1,并且需要将其放在循环的末尾。或者,您可以完全删除此行并改用它:

for (j = 0; j < col; j++) {
    printf("%d ", q[i][j]);
}

关于c - 将二维数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8678281/

相关文章:

c++ - 尝试指向自动对象时应该使用什么策略?

c++ - 帮助指针和传递链表作为参数, undefined reference C++

c - 在用 C 实现的多客户端单服务器程序中识别来自客户端的消息

c++ - 如何摆脱不安全的功能(sprintf,...)

c - fgetc 在轮询管道后仍然阻塞

php - 种子洗牌可以逆转吗?

c - 如何正确计算互相关?

java - 在java中生成唯一的随机数

java - 查找元素最大值最小的数组

将 8 位指针转换为 long