【发布时间】:2021-06-30 00:14:57
【问题描述】:
我最近正在实现一个以限制指针作为参数的函数 (my_copy()):
#include <stdio.h>
#include <stdlib.h>
void my_copy(int n, int * restrict p, int * restrict q) {
if (q == NULL) {
q = calloc(n, sizeof(int));
}
while(n-- > 0) {
*p++ = *q++;
}
// Ignore memory leak for now
}
int main() {
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int b[10];
// Copy a to b
my_copy(10, b, a);
for (int i = 0; i < 10; i++)
printf("%d ", b[i]);
printf("\n");
// Zero a
my_copy(10, a, NULL);
for (int i = 0; i < 10; i++)
printf("%d ", a[i]);
printf("\n");
}
为了在my_copy() 中实现“默认值”,我将分配给受限指针q。但是,我在https://en.cppreference.com/w/c/language/restrict 中看到不正确地使用限制会导致未定义的行为。特别是,我对“从一个受限指针到另一个受限指针的赋值是未定义的行为”这句话感到困惑。虽然我相信calloc() 不会返回受限指针,但我的程序是否没有未定义的行为?
【问题讨论】:
标签: c restrict-qualifier