cast to pointer to array - c vs. c++ (or gcc vs. g++) -
the following code compiles (and works expected) when compiled c code (gcc file suffix '.c') throws error when compiled c++ code (g++ of gcc file suffix '.cpp'):
int sum_square_matrix(int *matrix, int size) { int (*m)[size] = (int(*)[])matrix; ... }
the following error thrown when compiled g++ (or gcc suffix .cpp):
c_vs_cpp.c:4:32: error: cannot convert ‘int (*)[]’ ‘int (*)[(((sizetype)(((ssizetype)size) + -1)) + 1)]’ in initialization int (*m)[size] = (int(*)[])matrix;
the motivation behind such code processing square matrix double dimension array when dimension not known in advance.
so questions are:
- is there in c++ standard different c standard makes casting illegal?
- any other suggested method acheiving same goal (other manually accessing elements in matrix using ugly arithmetics , service functions). preferably common way supported in both c/c++.
- is there in c++ standard different c standard makes casting illegal?
yes. c++ standard doesn't allow variable length arrays †. c standard (since c99).
- any other suggested method acheiving same goal (other manually accessing elements in matrix using ugly arithmetics , service functions).
it's pretty trivial wrap ugly arithmetics inside helper type. simple example:
template<class t> struct matrix_view { t* matrix; size_t size; t* operator[](size_t i) { return matrix + * size; } }; template<class t> auto make_matrix_view(t* matrix, size_t size) { return matrix_view<t>{matrix, size}; } int sum_square_matrix(int *matrix, int size) { auto m = make_matrix_view(matrix, size); // ... }
with more boilerplate can make matrix_view
usable in standard algorithms , range based loops (only outer loop though; inner loop isn't quite trivial).
preferably common way supported in both c/c++.
perhaps design macro uses shown matrix_view in c++ , whatever cast method supported in c.
† gcc support vla language extension, why error message doesn't reason error. whatever reason, c++ implementation doesn't agree conversion. apparently if state size in cast:
int (*m)[size] = (int(*)[size])matrix;
i don't think has c++ standard though, difference between standard c , gcc implementation of vla extension c++.
Comments
Post a Comment