带有const参数的函数阵列



当我尝试修改传递给接收数组的数组的内容时,会发生什么,该数组的内容作为const parameter

接收数组

如果数据实际上是 const,您可以调用未定义的行为

#include <stddef.h>
void zlast(const int *s, size_t len) {
    int *ss = (int *)s; /* remove const'ness; silence warning */
    ss[len - 1] = 0; /* possible UB */
}
int main(void) {
    const int x[] = {1, 2, 3};
    int y[] = {0, 0, 0, 0, 0, 42};
    zlast(y, sizeof y / sizeof *y); /* ok */
    zlast(x, sizeof x / sizeof *x); /* UB */
    return 0;
}

最新更新