[英]Why do these two pointers access the same elements?
我正在開發一個MPI程序,每個過程都有以下代碼:
#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));
// Now I make some operations and I want to assign
// the value of recv_top and recv_left to 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) and (1,0) to 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) and (1,0) to recv_left!!
現在,當我檢查元素(1,0)的值時,問題就來了,我發現第一個調用也將recv_top的值保存在元素(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 at (%d,0) = %d\n", 1, CELL(this_data,1,0,bs_x+2,bs_y+2));
printf("Rank 4 value at (0,%d) = %d\n", 1, CELL(this_data,0,1,bs_x+2,bs_y+2));
}
//Rank 4 value at (1,0) = 12
//Rank 4 value at (0,1) = 12
接下來:
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 at (%d,0) = %d\n", 1, CELL(this_data,1,0,bs_x+2,bs_y+2));
printf("Rank 4 value at (0,%d) = %d\n", 1, CELL(this_data,0,1,bs_x+2,bs_y+2));
}
//Rank 4 value at (1,0) = 1024
//Rank 4 value at (0,1) = 1024
同時更新(1,0)。
他們不應該這樣做,因為他們不一樣:
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))
有什么想法我做錯了嗎?
代碼#define CELL(A,X,Y,MX,MY) (*(A+Y*MX+X))
應該是
#define CELL(A,X,Y,MX,MY) ( *( (A) + (Y) * (MX) + (X) ) )
注意括號!
順便說一句,為什么不使用內聯函數?有了內聯函數,您將獲得更好的代碼。
在您的版本中,代碼
CELL(this_data, 0, i+1, bs_x+2, bs_y+2)
擴展為:
*(this_data+i+1*bs_x+2+bs_y+2)
這似乎與您期望的不同
更新
我仍然建議您使其成為內聯函數!
inline void CELL(int* A, int X, int Y, int MX, int MY, int newValue)
{
int * cell = A + Y * MX + X;
*cell = newValue;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.