【问题标题】:Restricted pointer assignments受限指针分配
【发布时间】:2026-01-31 12:30:01
【问题描述】:

我有一个关于受限指针分配的问题。有关具体问题,请参阅代码中的 cmets。总的来说,我只是想知道限制是合法的(我已经阅读了标准,但仍有疑问:-(

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];
    }
}

感谢您的帮助!

【问题讨论】:

  • “将R 的值带出块”是什么意思?您的代码根本不会修改R,在R 范围内的所有地方都有R == Q。顺便说一句,在您提出问题后几分钟就接受答案是长期用户建议反对的。

标签: c pointers alias c99 restrict-qualifier


【解决方案1】:

由于被修改的对象(在第一行分配的数组)没有通过左值表达式修改,除了涉及受限指针,R 在声明 R 的那个块中,我认为你的代码示例定义明确。

如果Q 是受限指针,则示例将是未定义的。

【讨论】:

  • 再次感谢您的帮助...再次! :)
  • 不客气 - 只是意识到我发现 restrict 定义的措辞很难理解(可能和你一样),所以我对我的回答可能没有信心与其他答案一样强大...