限制指针分配

时间:2010-09-27 17:30:48

标签: c pointers alias c99 restrict-qualifier

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

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

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

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

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