When I compile the following code with gcc
and g++
, g++
gives error and not gcc
. Note that the code converts from int (*)[4]
to int (*)[]
(which is pointer to incomplete array type).
int arr[4];
int (*p_arr)[] = &arr;
As discussed in Incomplete array type? , C
language allows this conversion. But why does C++
disallow this and gives the error error: cannot convert 'int (*)[4]' to 'int (*)[]' in assignment
. I know C++ is more type-safe than C, but does this assignment is really type-unsafe, because the later dereference of the pointer (eg sizeof(*p_arr)
) anyway gives error in C
as well?
The conversion by itself is safe, but keep in mind that the same rule in C that allows this conversion also allows it in the opposite direction.
int main() {
int array[4] = {0};
int (*ptr4)[4] = &array;
int (*ptrN)[] = ptr4;
int (*ptr5)[5] = ptrN; /* oh dear */
}
This is clearly bad. C++ has removed this rule, the rule that says int[4]
and int[]
are compatible types, and pretty much got rid of the concept of compatible type.
Some specific conversions that are safe are being considered for inclusion in a future version of C++ . They include your conversion as well.
Yes, this assignment does is really type-unsafe.
In C++, array types include the dimension. Always.
(Mostly.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.