Reputation:
What would be the output of the following program?
int main(void) {
int n[3][3] = {
2, 4, 3,
6, 8, 5,
3, 5, 1
};
int i, *ptr;
ptr = n;
for (i = 0; i <= 8; i++)
printf("\n%d", *(ptr + i));
}
Here what does n
means w.r.t to two dimensional array? And what ptr will have? I am having lot of confusion using pointers with Array.
Output is coming as 4 everytime. I am trying to understand why it is printing 4 everytime?
Any explanation will help me a lot.
Upvotes: -1
Views: 2263
Reputation: 2973
ptr is a pointer that "points" to the first element of the 'n' matrix. You make it doing:
ptr = n[0];
You can't do:
ptr = n;
because 'n' is an "array" of "arrays" (the first array store 2, 4 and 3, the second 6, 8 and 5, and so on...)
When you declare the 'n' two-dimensional array, the elements are stored in memory in linear order (one integer allocation after another) and thats the reason why you can make 'n' point to one element (the first element in this case) and then make it point to the next element (by adding 1 to the pointer, this is called "pointer arithmetic").
This is the little correction to make the program works in the right way:
#include <stdio.h>
int main(void) {
int n[3][3] = {
2, 4, 3,
6, 8, 5,
3, 5, 1
};
int i, *ptr;
ptr = n[0];
for (i = 0; i <= 8; i++)
printf("\n%d", *(ptr + i));
}
The output wil be:
2 4 3 6 8 5 3 5
Upvotes: 3
Reputation: 7610
ptr=n;
will assign the starting address of the 2D array n
to the pointer variable ptr
. In order to avoid the warning assign ptr = &n[0][0];
. Even though both n and &n[0][0] gives you the same address their types are different. n
is the starting address of the 2D array n
and &n[0][0]
is the address of the first element of the array which is n[0][0]
.
The following modified program will tell you the difference,
int main()
{
int n[3][3] = {2, 4, 3, 6, 8, 5, 3, 5, 1};
int i, *ptr1, (*ptr2)[3];
ptr1 = &n[0][0];
ptr2=n;
printf("\n%p",ptr1);
printf("\n%p",ptr2);
printf("\n%p",++ptr1);
printf("\n%p",++ptr2);
}
Initially both ptr1
and ptr2
will print the same address.
But after incrementing ptr1
and ptr2
will point to different addresses as their types are different.
Upvotes: 0
Reputation: 4245
Output:
2 4 3 6 8 5 3 5 1
print all elements in arry orderly. array is contiguous, ptr=n; alloted address of n;
n gives address of first row or address of first element.
printf("%d %d %d",n,&n[0],&n[0][0]);
gives same address.
arr[i] is same as *(arr+i)
n
n[0] or(n+0)
&n[0][0]
|
|
v
2 4 3 6 8 5 3 5 1
| | | |
|[0][0] | | |
|--row 0-------| row 1 |----row 2----|
each time when you do ptr+i its doing pointer arithmetic adds sizeof(int) to ptr results in next element in memory.
Upvotes: 1