Search code examples
cpointersrestrict-qualifier

Passing restrict qualified pointers to functions?


Restrict qualified pointers were explained to me as having a rule: Any object accessed by the pointer and modified anywhere is only ever accessed by the pointer. So the following does not work, right?

void agSum( int * restrict x, int n ){
   for(int i=0; i<n-1; i++) x[i+1] += x[i];
}

int SumAndFree( int * restrict y, int n ){
    agSum(y);
    printf("%i",y[n-1]);
    free(y);
}

So, I guess this is invalid because y[n-1] is modified somewhere not directly accessed from the restrict pointer y, and it is read by y.

If this is right, how can you call functions when the input pointer is restrict qualified? It seems like the function can't do anything without violating the restrict rule.

Is it another violation to free the restrict pointer? That is kind of a modification, I guess.

Thanks in advance!


Solution

  • Your code is correct. When SumAndFree calls agSum, it passes a pointer derived from y . So all of the accesses under the block of SumAndFree's body are done using pointers derived from y.

    It's fine to call free too.

    Your functions don't do any reading or writing other than x and y, so restrict actually serves no purpose in this exact case.