lang.cpp | Pointer to Array

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int *n = (int *)malloc(24);
  n[0] = 1;
  n[1] = 5;
  n[2] = 10;
  n[3] = 9;
  n[4] = 13;
  n[5] = 66;
  int (*m)[2] = (int (*)[6])n;
  printf("m[0][0] = %d\n", m[0][0]);
  printf("m[0][1] = %d\n", m[0][1]);
  printf("m[0][2] = %d\n", m[0][2]);
  printf("m[1][0] = %d wrong\n", m[1][0]);
  printf("m[1][1] = %d wrong\n", m[1][1]);
  printf("m[1][2] = %d wrong\n", m[1][2]);
  printf("m[0][0] = %d\n", m[0][0]);
  printf("m[0][1] = %d\n", m[0][1]);
  printf("m[1][0] = %d\n", m[1][0]);
  printf("m[1][1] = %d\n", m[1][1]);
  printf("m[2][0] = %d\n", m[2][0]);
  printf("m[2][1] = %d\n", m[2][1]);
  printf("*(int *)m = %d\n", *(int *)m);
  printf("*(int *)(m + 1) = %d\n", *(int *)(m+1));

}

/*
output:
m[0][0] = 1
m[0][1] = 5
m[0][2] = 10
m[1][0] = 10 wrong
m[1][1] = 9 wrong
m[1][2] = 13 wrong
m[0][0] = 1
m[0][1] = 5
m[1][0] = 10
m[1][1] = 9
m[2][0] = 13
m[2][1] = 66
*(int *)m = 1
*(int *)(m + 1) = 10
*/
Comments