Reputation: 883
I have the following code :
#include<stdio.h>
void func(int [][3]);
int main(){
int a[][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
func(a);
printf("%d", a[2][1]);
}
void func(int b[][3]){
++b;
b[1][1] = 17;
}
Problem :
I expected the printf statement to print 8 but its printing 17.
I dont understand why ?
Thanks
Upvotes: 3
Views: 98
Reputation: 5425
You can take a look on memory layout of your code with extended code:
#include <stdio.h>
void print_addr(int b[][3])
{
for (int i = 0 ; i < 3 ; i++) {
for (int j = 0 ; j < 3 ; j++)
printf("%p ", &b[i][j]);
printf("\n");
}
}
void func(int b[][3]){
print_addr(b);
printf("sizeof(b): %d sizeof(b[0][0]) %d\n", sizeof(b), sizeof(b[0][0]));
++b;
print_addr(b);
b[1][1] = 17;
}
int main()
{
int a[][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
func(a);
printf("%d\n", a[2][1]);
}
It will show that after the shift you make, the b[1][1]
address will point into a[2][1]
cell because of b
is a pointer to lines of array and b++
shifts down by one line.
Also you pass value by pointer, so function func
accesses the same memory where a
sits.
If I may suggest, just print everything while you learn, and also take a look on this nice presentation: http://www.slideshare.net/olvemaudal/deep-c?qid=1fcb7c99-e916-4bcd-baa2-1a1f974d1c68
Upvotes: 5
Reputation: 61
In C, array parameters like int b[][3] are just pointers to the memory where the array resides. So an update in func() to the array persists, since you're accessing the same memory in main and func().
b currently points to first array {1, 2, 3}. ++b does pointer arithmetic, so b increments to point to the next array {4, 5, 6}. So b[1][1] will update main's a[2][1], which is what you printed. Try the following code to see that you are indeed updating the same memory addresses.
#include<stdio.h>
void func(int [][3]);
int main(){
int a[][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
printf("%p\n", a+1);
func(a);
printf("%d\n", a[2][1]);
}
void func(int b[][3]){
++b;
printf("%p\n", b);
b[1][1] = 17;
}
Upvotes: 4
Reputation: 122493
Note ++b
in func()
, after this, b
(originally pointing to a[0][0]
), now points to a[1][0]
, so the following
b[1][1] = 17;
modifies a[2][1]
outside.
Upvotes: 7