Unable to understand the behavior of arrays

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 output to print 8, but it prints 17.
I don't understand why?

thank

+3


source to share


3 answers


You can take a look at the memory layout of your 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 is made, the address b[1][1]

will point to the cell a[2][1]

, because it b

is a pointer to the rows of the array, and b++

is shifted down one row.



Also, you are passing the value by pointer, so the function func

accesses the same memory where it sits a

.

If I can suggest, just print everything while you study and also take a look at this nice presentation: http://www.slideshare.net/olvemaudal/deep-c?qid=1fcb7c99-e916-4bcd-baa2-1a1f974d1c68

+5


source


The 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;

      



changes a[2][1]

outside.

+7


source


In C, array parameters such as int b [] [3] are simply pointers to the memory in which the array resides. This way, the update in func () for the array persists as you access the same memory in main and func ().

b is currently pointing to the first array {1, 2, 3}. ++ b does pointer arithmetic, so b increments to point to the next array {4, 5, 6}. Thus, b [1] [1] will update the main file [2] [1] that you typed. 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;
}

      

+4


source







All Articles