c - Why do these two pointers access the same elements? -
i'm working on mpi program , have following code each of processes:
#define cell(a,x,y,mx,my) (*(a+y*mx+x)) int bs_x = 1; int bs_y = 1; int *this_data=calloc((bs_y+2)*(bs_x+2), sizeof(int)); //... int *recv_top = calloc(bs_x, sizeof(int)); int *recv_left = calloc(bs_x, sizeof(int)); // make operations , want assign // value of recv_top , recv_left this_data for(i=0; i<bs_x; ++i) cell(this_data, i+1, 0, bs_x+2, bs_y+2) = recv_top[i]; // sets both (0,1) , (1,0) recv_top!! for(i=0; i<bs_x; ++i) cell(this_data, 0, i+1, bs_x+2, bs_y+2) = recv_left[i]; // again sets both (0,1) , (1,0) recv_left!! now problem comes when check value of element (1,0) , found out first call saves value of recv_top in element (0,1):
for(i=0; i<bs_x; ++i) cell(this_data, i+1, 0, bs_x+2, bs_y+2) = recv_top[i]; if (rank == 4) { printf("rank 4 value @ (%d,0) = %d\n", 1, cell(this_data,1,0,bs_x+2,bs_y+2)); printf("rank 4 value @ (0,%d) = %d\n", 1, cell(this_data,0,1,bs_x+2,bs_y+2)); } //rank 4 value @ (1,0) = 12 //rank 4 value @ (0,1) = 12 and next:
for(i=0; i<bs_x; ++i) cell(this_data, 0, i+1, bs_x+2, bs_y+2) = recv_left[i]; if (rank == 4) { printf("rank 4 value @ (%d,0) = %d\n", 1, cell(this_data,1,0,bs_x+2,bs_y+2)); printf("rank 4 value @ (0,%d) = %d\n", 1, cell(this_data,0,1,bs_x+2,bs_y+2)); } //rank 4 value @ (1,0) = 1024 //rank 4 value @ (0,1) = 1024 updates (1,0).
they shouldn't since not same:
cell(this_data, 0, i+1, bs_x+2, bs_y+2) = (*(this_data+(i+1)*(bs_x+2)) cell(this_data, i+1, 0, bs_x+2, bs_y+2) = (*(this_data+i+1)) any ideas i'm doing wrong?
the code #define cell(a,x,y,mx,my) (*(a+y*mx+x)) should be
#define cell(a,x,y,mx,my) ( *( (a) + (y) * (mx) + (x) ) ) note parenthesis!
btw, why not use inline function?with inline function have better code.
in version code
cell(this_data, 0, i+1, bs_x+2, bs_y+2) expands into:
*(this_data+i+1*bs_x+2+bs_y+2) which seems different you'd expect
update
i still suggest make inline function!
inline void cell(int* a, int x, int y, int mx, int my, int newvalue) { int * cell = + y * mx + x; *cell = newvalue; }
Comments
Post a Comment