Passing restrict qualified pointers to functions?

人盡茶涼 提交于 2019-12-10 18:24:59

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/36323156/passing-restrict-qualified-pointers-to-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!