我一直认为像const int *a
手段这样的语句a
是指向数据的int
指针,const
因此不应该能够修改它指向的值。事实上,如果你这样做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;
}
为什么允许这样做?这是演员阵容的原因吗?当我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 *’