Skip to content

Instantly share code, notes, and snippets.

@hadashiA
Created July 15, 2012 18:35
Show Gist options
  • Save hadashiA/3118070 to your computer and use it in GitHub Desktop.
Save hadashiA/3118070 to your computer and use it in GitHub Desktop.
配列のポインタと、配列の特定の要素のポインタのオフセットから、インデックスを逆算する
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int matrix[50][50];
int x, y;
for (x = 0; x < 50; x++) {
for (y = 0; y < 50; y++) {
matrix[x][y] = x + y;
}
}
int *entity = &matrix[3][17];
printf("entity %d (%p) (%p)\n", *entity, entity, matrix);
unsigned long offset = (unsigned long)entity - (unsigned long)matrix;
int numOffset = offset / sizeof(int);
x = numOffset / 50;
y = numOffset % 50;
printf("offset: %ld x:%d y:%d\n", offset, x, y);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment