I have just started diving into pointers in C and I can't understand why 14 is the output.
I have the given code:
#include<stdio.h>
#include<stdlib.h>
#define N 3
typedef int(*MyType1)[N];
typedef int(*MyType2)[N][N];
int main(int argc, int *argv[]){
int m1[][N] = { 21,122,-13,14,56,36,17,78,92 };
int m2[][N] = { 11,9,43,17,32,99,127,34,69 };
MyType1 p1[] = { m1 1,m2 2,m1 2,m2,m1,m2 1};
MyType2 p2[] = { &m2, &m1 };
printf("%d\n", **(p2[1][0] 1));
return 0;
}
My thought was:
**(p2[1][0] 1)
is equivalent to **(&m1[0] 1)
.
Then, &m1[0]
is the address of the first element in m1 (21), plus one increments the address to the number next to it (122).
I noticed that every plus one accessed the n 3 number in m1 (goes down a row in m1?) --> The question is why.
CodePudding user response:
Well...
p[1]
is a pointer to m1
.
m1
might also have been initialized: {{21,122,-13},{14,56,36},{17,78,92}}
.
So p[1][0]
is a pointer to the first array: {21, 122, -13}
but then we do some pointer arithmetic and point to the next array: {14,56,36}
and when we dereference that we get the first element which is... 14
.