次のコードがあるとします。
#include <stdlib.h>
static double A[100][100];
const double* func(size_t m) {
return A[m];
}
int main() {
double * x = func(5);
x[10] = 20.4;
}
GCC 4.8.1 レポート:
foo.cc:10:21: error: invalid conversion from ‘const double*’ to ‘double*’ [-fpermissive]
double * x = func(5);
^
そしてClang 3.3レポート:
foo.cc:10:11: error: cannot initialize a variable of type 'double *' with an rvalue of type 'const double *'
double * x = func(5);
^ ~~~~~~~
そして、ComicSansMS のコメントを具体化するために、彼が応答しているコメントが削除されたため:
typedef double* ptr;
const ptr func(size_t m) {
return A[m];
}
このコードは、上記のコードと同じではありません。const ptr
double への定数ポインターです。元のコードは、定数 double へのポインターを参照します。
次のようにして、これらの行に沿って何かを行うことができます。
typedef double* ptr;
typedef const double* cptr;
cptr func(size_t m) {
return A[m];
}
int main() {
ptr x = func(5);
x[10] = 20.4;
}
エラーを報告するもの:
so.cc:27:6: error: cannot initialize a variable of type 'ptr' (aka 'double *') with an rvalue of type 'cptr' (aka 'const double *')
ptr x = func(5);
^ ~~~~~~~