Reputation: 19
#include <stdio.h>
int main( int argc, char *argv[] )
{
int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int *b = a[1];
b[2] = 99;
for ( int i = 0; i < 3; i++ )
{
printf( "%d,", a[1][i] );
}
}
ouput is :4,5,99,
#include <stdio.h>
int main( int argc, char *argv[] )
{
int a[3] = { 1, 2, 3 };
int b = a[1];
b = 99;
for ( int i = 0; i < 3; i++ )
{
printf( "%d,", a[i] );
}
}
output is :1,2,3
why I got such different results? i thought in the first part a should also stay unchanged
Upvotes: 1
Views: 142
Reputation: 1375
NOTE: Here the int is assumed to be 2 bytes.
case 1: int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Will be allocated as follows:
a[0]:
a[0][0] a[0][1] a[0][2]
+----+----+----+
| 1 | 2 | 3 |
+----+----+----+
1000 1002 1004
a[1]:
a[1][0] a[1][1] a[1][2]
+----+----+----+
| 4 | 5 | 6 |
+----+----+----+
1006 1008 1010
a[2]:
a[2][0] a[2][1] a[2][2]
+----+----+----+
| 7 | 8 | 9 |
+----+----+----+
1012 1014 1016
int *b = a[1];
b
+----+
|1006| // 1006 is the address of the a[1]
+----+
11000
b[2] = 99;
b[2] is the third element in the second array which has address location 1010 .
since b is a pointer to an second(i.e, a[1]) array and hence b[2] is nothing but *(b+2) its as offset from the first element and therefore a[1][2] will get afftected.
b
+----+
|1006| // 1006+2 will be the location that is 1010 (as int takes 2 bytes). Here
+----+ // address location are taken for just reference purpose.
11000
a[1]:
a[1][0] a[1][1] a[1][2]
+----+----+----+
| 4 | 5 | 22 |
+----+----+----+
1006 1008 1010
printf( "%d,", a[1][i] );
Outputs: 4,5,99
case 2 :
int a[3] = { 1, 2, 3 };
a[3]:
a[0] a[1] a[2]
+----+----+----+
| 1 | 2 | 3 |
+----+----+----+
1000 1002 1004
int b = a[1];
b
+----+
| 2 |
+----+
5000
b = 99;
The value of b gets overwritten.
b
+----+
| 99 | // Since b is a normal variable and hence will not affect array memory location.
+----+
5000
printf( "%d,", a[i] );
As you can see the array does not got affected.
Output: 1,2,3
Upvotes: 1
Reputation: 19874
int *b
b is a pointer which points to the second row of your 2D array and it has the memory location of the row a[1]
and it can change the contents of the memory location by dereferencing it.
b[2] = *(b+2) = 99;
Whereas
int b;
b is not a pointer. You can't reference a variable like a pointer to store value in particular memory location. Hence you see that the value is not changed when you do
b = 99;
in the second code snippet
Upvotes: 1
Reputation: 65770
When int *b = a[1]
executes, b
is pointing to the same memory location as a[1]
, i.e. an int[3]
. Thus, when you update b[2]
, a[1][2]
is also updated.
In the second case, int b = a[1]
sets b
to be the same value as a[1]
, but at a different memory location, so when b
is updated, a
is not.
I would read up more about how pointers work in C.
Upvotes: 4