我一直认为像const int *a
这样的语句意味着a
是一个指向const
的int
指针数据,因此不应该能够修改它指向的值。实际上,如果您执行 const int a [] = {1,2,3}
然后发出 a[0] = 10
,您将遇到编译器错误。
然而,令我惊讶的是,以下代码在没有任何警告的情况下编译并且运行正常。
#include <stdio.h>
#include <string.h>
int main (){
const int a [] = {1, 1, 1};
const int b [] = {2, 2, 2};
memcpy((void*) &a[0], (const void*)&b[0], 3*sizeof(int));
int i;
for (i=0; i<3; i++) printf("%d\n",a[i]);
return 0;
}
为什么允许这样做?这是 Actor 的原因吗?当我执行 memcpy(&a[0], (const void*)&b[0], 3*sizeof(int));
编译器会立即生成以下警告:
cpy.c: In function ‘main’:
cpy.c:9:3: warning: passing argument 1 of ‘memcpy’ discards ‘const’ qualifier from pointer target type [enabled by default]
/usr/include/string.h:44:14: note: expected ‘void * __restrict__’ but argument is of type ‘const int *’
最佳答案
您告诉编译器在执行强制转换时忽略初始声明。它听了。但是,这并不意味着您的程序是正确的。修改最初声明为 const
的内容会导致未定义的行为(例如,编译器可以随意将该数据存储在只读内存中)。
C 没有牵你的手。如果您选择做一些危险的事情,那么它会让您这么做。
关于c - 带有指向 const 数据的目标指针的 memcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12309600/