2010-09-27 72 views
3

我有一個關於限制指針分配的問題。有關具體問題,請參閱代碼中的註釋。總體來說,我只是想知道什麼是法律與限制(我讀過的標準,但仍然有:-(限制指針分配

int* Q = malloc(sizeof(int)*100); 

{ 
    int* restrict R = Q; 

    for(int j = 0; j < rand()%50; j++) 
    { 
     R[j] = rand(); 
    } 

    Q = R; // The standard says assigning restricted child pointers to their parent is illegal. 
      // If Q was a restricted pointer, is it correct to assume that this would be ILLEGAL? 
      // 
      // Since Q is unrestricted, is this a legal assignment? 
      // 
      // I guess I'm just wondering: 
      // What's the appropriate way to carry the value of R out of the block so 
      // the code can continue where the above loop left off? 
} 

{ 
    int* S = Q; // unrestricted child pointers, continuing where R left off above 
    int* T = Q+1; // S and T alias with these assignments 

    for(int j = 0; j < 50; j++) 
    { 
     S[j] = T[j]; 
    } 
} 

感謝的問題對你有所幫助!

+0

「將R的值從塊中移出」是什麼意思?你的代碼根本不會修改'R',在'R'範圍內的所有地方都有'R == Q'。順便說一句,在你提出問題後僅僅幾分鐘接受答案是長期用戶推薦的問題。 – 2010-09-27 17:57:22

回答

1

由於被修改的對象(數組在第一行分配的)不通過左值表達式修改,除非涉及受限指針,RR被聲明該塊,我認爲在你的例子的代碼是明確定義的。

如果Q被受限制的指針,這個例子是不確定的。

+0

再次感謝您的幫助! :) – Andrew 2010-09-27 17:48:56

+0

不客氣 - 只是意識到我發現'restrict'定義的措辭很難遵循(可能和你一樣),所以我對我的回答的信心可能不如其他答案... – 2010-09-27 18:00:21