[英]A pointer to Multidimensional Array
/* Demonstrates passing a pointer to a multidimensional */
/* array to a function. */
#include <stdio.h>
void printarray_1(int (*ptr)[4]);
void printarray_2(int (*ptr)[4], int n);
int main(void)
{
int multi[3][4] = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} };
// ptr is a pointer to an array of 4 ints.
int (*ptr)[4], count;
// Set ptr to point to the first element of multi.
ptr = multi;
// With each loop, ptr is incremented tto point to the next
// element (that is, the next 4-elements integer array) of multi.
for (count = 0; count < 3; count++)
printarray_1(ptr++);
puts("\n\nPress Enter...");
getchar();
printarray_2(multi, 3);
printf("\n");
return 0;
}
void printarray_1(int (*ptr)[4])
{
// Prints the elements of a single 4-element integer array.
// p is a pointer to type int. You must use a typecast
// to make p equal to the address in ptr.
int *p, count;
p = (int *)ptr;
for (count = 0; count < 4; count++)
printf("\n%d", *p++);
}
void printarray_2(int (*ptr)[4], int n)
{
// Prints the elements of an n by 4-element integer arrray.
int *p, count;
p = (int *)ptr;
for (count = 0; count < 4; count++)
printf("\n%d", *p++);
}
In the definition of printarray_1 & 2 functions, the int pointer p is assigned to (int *)ptr.在 printarray_1 & 2 函数的定义中,int 指针 p 被分配给 (int *)ptr。 why?
为什么?
In the pointer declaration of the main function, the parenthesis puts *ptr in a higher precedence than [4].在主 function 的指针声明中,括号将 *ptr 置于比 [4] 更高的优先级。 but (int *)ptr does not make sense to me.
但是 (int *)ptr 对我来说没有意义。 Would you please explain why?
你能解释一下为什么吗?
The syntactically and semantically correct way to obtain p
from ptr
is:从
ptr
获得p
的语法和语义正确的方法是:
p = *ptr;
... as you are trying to extract an array int p[4]
(declared as int *p
) from a pointer to an array int(*ptr)[4]
. ...当您尝试从指向数组
int(*ptr)[4]
的指针中提取数组int p[4]
(声明为int *p
)时。 This eliminates the need for any casting.这消除了对任何铸造的需要。
(int *)p it the same like int *p (int *)p 和 int *p 一样
i advice you to make a simple program and try it我建议你制作一个简单的程序并尝试一下
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.