以下代码部分有效。请帮忙找出错误
#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]地址等。
问题:
当我的二维数组被创建时,空间被分配给这些 'a','a[0]','a[1]','a[2]','a[3]' Is'不是吗??除了空间分配给a[0][0],a[0][1],a[1][0]......a[3][4]
为什么我无法检索“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/