Hi, all I am having a trouble with pointer and multi-dimensional array.
I wrote the same thing but I see different output. below is the code
Code:
#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];
int *p;
int count = 0;
/* set ptr to the first element of multi */
ptr = multi;
/* with each loop, ptr is incremented to point to the nex */
/* element (that is, the next 4 element integer array) of multi. */
for ( count=0; count < 3; count++ )
{
printarray_1(ptr++);
}
puts("\n\nPress Enter...");
getchar();
printarray_2(multi, 3);
printf("\n");
puts("\n\nPress Enter...again");
getchar();
printf("\n\n");
/*
from here it print out something crazy as you can see the output below.
*/
p = (int *) ptr;
for (count = 0; count < (4*3); count++)
{
printf("\n%d", *p++);
}
printf("\n\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("%d\n", *p++);
}
void printarray_2 (int (*ptr)[4], int n)
{
int *p, count;
p = (int *) ptr;
for (count = 0; count < (4*n); count++)
{
printf("\n%d", *p++);
}
}
Here is the out put
Code:
1
2
3
4
5
6
7
8
9
10
11
12
Press Enter...again
1
2
3
4
5
6
7
8
9
10
11
12
-858993460
1245112
4267446
1
3493392
3486624
2018114650
1028656064
29897040
2147348480
3579545
0
Press any key to continue . . .