gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:15:16 26 4
gpt4 key购买 nike

在以下代码中, 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数组?

最佳答案

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

在该示例中,const int a[3]; 的元素通过调用 memset 来填充,该调用会生成警告,因为 memset 函数接受一个指向 void 的(非常量)指针,编译器必须隐式丢弃 const

C11 6.7.3 类型限定符:

脚注 132:

The implementation may place a const object that is not volatile in a read-only region of storage. Moreover, the implementation need not allocate storage for such an object if its address is never used.

关于c - 在 `const` 数组上使用 memset() 函数是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47405872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com