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

时间:2017-11-21 05:32:35

标签: 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;
}

memset数组上使用const是否合法?

1 个答案:

答案 0 :(得分:5)

请勿尝试修改声明为const的数组的内容,否则结果为未定义的行为

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

C11 6.7.3类型限定符:

脚注132:

  

实施可能会将const对象放在volatile中   只读存储区域。而且,实施不需要   如果从未使用过地址,则为此类对象分配存储空间。