我一直認爲像const int *a
這樣的說法意味着a
是int
指向const
數據,因此不應該能夠修改它指向的值。事實上,如果你做const int a [] = {1,2,3}
,然後問題a[0] = 10
你會得到編譯器錯誤。memcpy與目標指針常量數據
然而,令我驚訝的是,下面的代碼沒有任何警告,編譯運行得很好。
#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 *’
報復指出 –