mgs5 紧急任务失败:C语言 指针

来源:百度文库 编辑:中科新闻网 时间:2024/04/30 14:36:13
/* 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;

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 four-element integer array. */
/* p is a pointer to type int. You must use a type cast */
/* 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 four-element integer array. */

int *p, count;
p = (int *)ptr;

for (count = 0; count < (4 * n); count++)
printf("\n%d", *p++);
}

——————————————————————
printarray_1(ptr++);是什么意思?
ptr指向multi[0][0]的地址,为什么在第一次循环就要ptr++ ?

printarray_1(ptr++)的意思是
将ptr所指向的值:1,2,3,4传给printarray_1(),
然后让ptr自加一,即让ptr指向5,6,7,8。
第一次循环就要ptr++的原因,是当第二次调用的时候
ptr传给printarray()的值为:5,6,7,8。

这其实是 x++ 的一个应用实例,在实际应用中
可以灵活采用x++或者++x可以让程序简洁
但是程序的可读性可能会降低。