指针运算和C 2-D数组? [英] Pointer arithmetic and 2-D array in c?
问题描述
我是新的C和被困的如何多维数组传递给函数。我也明白,你必须通过列大小,这样,如果你想从走了[0] [0]
到 A [1] [ 0]
它可以计算一维数组的大小,可以跳过去。
I am new to C and got stuck on "How to pass multidimensional array to a function". I do understand that you have to pass column size so that if you want to go from a[0][0]
to a[1][0]
it can calculate the size of 1-D array and can jump over it.
我已经写了一个小程序:
I have written a small program:
#include<stdio.h>
void foo(char[][2]);
int main()
{
char arr[2][2] = {'a','b','c','d'};
foo(arr);
return 0;
}
void foo(char temp[][2])
{
temp++;
printf("%c",*temp);
}
我预计这一code将打印的信 C
,因为温度
最初指向'A'
,一旦我们增加它,它会跳过第一个一维数组,然后转到第二个1-D数组的第一个元素是'C
。但它不是这样的,我猜。
I expected that this code will print the letter c
, since temp
initially points to 'a'
and once we increment it, it will skip over first 1-d array and go to first element of second 1-d array which is 'c'
. But it does not work that way I guess.
请解释编译器如何计算这些地址。
Please explain the how compiler computes these addresses.
推荐答案
有关函数的参数字符临时[] [2]
,温度
衰变为指针。但仅用于第一(外)尺寸。因此,它实际上是一个的指针数组 [2]
字符
的的
For function argument char temp[][2]
, temp
decays to a pointer. But only for the first (outer) dimension. So it is effectively a pointer to array [2]
of char
.
递增指针将其推进到一个新的外部指标,因为你已经承担。
Incrementing the pointer will advance it to the next outer index, as you already assumed.
所以,你要么必须使用(*临时)[0]
或 **温度
来获得第一个元素。 **温度
的作品,因为 *温度
本身就是一个数组,所以它衰变为指针的第一个元素内部数组。第二个(左) *
然后取消引用该指针: C
So, you either have to use (*temp)[0]
or **temp
to get the first element. **temp
works, because *temp
is an array itself, so it decays to a pointer to the first element of the inner array. The second (left) *
then dereferences this pointer: c
.
需要注意的是,它allthough使用相同的语法像的char **温度
,它们是根本不同的。指针是不是一个数组,在这里,递增温度
将仅由一个指针的大小,这是不是你想要的进步。
Note that, allthough it uses the same syntax like char **temp
, they are fundamentally different. A pointer is not an array and here, incrementing temp
will only advance by the size of a pointer, which is not what you want.
注意,初始化将更好地根据2 simensional性质是:
Note that the initializer would better be according to the 2-simensional nature:
{ { 'a', 'b' } , { 'c', 'd' } }
这确保您获得正确的值的内部数组,是很好的做法。在非嵌套形式省略值将导致错误的序列用于内阵列。当已启用推荐的警告( -Wall
)的至少,GCC发出警告缺少括号。
This ensures you get the correct values for the inner arrays and is good practice. Omitting a value in the non-nested form will result in wrong sequence for the inner array. When having enabled the recommended warnings (-Wall
) at least, gcc warns about missing braces.
这篇关于指针运算和C 2-D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!