c++ - Pointer to 2D array. Why does this example work? -


I have this code example, but I do not understand that when changing the values ​​in the array, outputUsingArray () The original array is changing.

I think that in outputUsingArray () , the value of the array is expected to change, only for the local copy of the array.

Why not do that?

However, this is the behavior that I would like, but I do not understand why it works.

  Add # & lt; Stdlib.h & gt; # Include & lt; Stdio.h & gt; Zero Output Usage (int array [] [4], int n_rows, int n_cols) {int i, j; Printf ("use array output \ n"); For {i = 0; i & lt; n_rows; i ++} {for (j = 0; j & lt; n_cols; j ++) {// can be used either // printf ("% 2d ", array [i] [j]); Printf ("% 2d", * (* (array + i) + j)); } Printf ("\ n"); } Printf ("\ n"); Array [0] [0] = 100; Array [2] [3] = 200; } Zero outputupping pointers (at (array *) [4], int n_ro, int nucleos) {int i, j; Printf ("OUre to use array with pointer i.e. int (* array) [4] \ n"); (I = 0; i & lt; n_rows; i ++) {for (j = 0; j & lt; n_cols; j ++) {printf ("% 2d", * (* (array + i) + J)); } Printf ("\ n"); } Printf ("\ n"); } Int main () {int array [3] [4] = {{1, 2, 3}, {4, 5, 6, 7}, {8, 9, 10, 11}}; OutputUsingPointer ((int (*) [4]) array, 3, 4); OutputUsingArray (array, 3, 4); Printf ("0,0:% i \ n", array [0] [0]); Printf ("2,3:% i \ n", array [2] [3]); Return 0; }  

passing int [] actually pointing to the first element of the array Used to be . Passing int * also indicator passing the first element of the array.

They are the same.

Since both of them point to the same part of the change of memory, changing one from one will change the other.


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -