在`const`数组上使用memset()函数是否合法?

msc*_*msc -4 c arrays const memset

在以下代码中,函数const清除数组的元素memset.

#include <stdio.h>
#include <string.h>

int main() {
    const int a[3] = {1, 2, 3};
    memset(a, 0, sizeof(a));
    printf("%d %d %d\n",a[0],a[1],a[2]);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

memsetconst阵列上使用是合法的吗?

msc*_*msc 5

.

不要尝试修改声明为的数组的内容const,否则结果是未定义的行为.

在该示例中,const int a[3];memset生成警告的调用填充了元素,因为memset函数将(非常量)指针指向void,编译器必须隐式抛弃const.

C11 6.7.3类型限定符:

脚注132:

实现可以放置const不在volatile只读存储区域中的对象.此外,如果从不使用其地址,则实现不需要为这样的对象分配存储.

  • The quoted passages are irrelevant as the code contains a constraint violation (5认同)