1

Can I cast an an array of arrays int arr[4][10] to an array of pointers int *arr[4]?

How should I write the cast?

1

2 Answers 2

2

Can I cast an an array of arrays int arr[4][10] to an array of pointers int *arr[4]?

No.

You can cast int arr[4][10] to int (*arr)[10] though — or rather the former is implicitly convertible to the latter that you don't require any explicit cast at all.

BTW, it is better if you avoid using raw arrays to begin with. Prefer std::array<T,N> instead.

In this case, you could use std::array<std::array<int,10>,4>.. and then try designing your code in such a way which doesn't require casting at all.

Sign up to request clarification or add additional context in comments.

15 Comments

I'm actually integrating with some low level library code. So just to make it clear, I can only cast arr to a pointer to an array of size 10 (basically &arr[0]). Is that right?
@Xyand: Yes, that is right :-). Since type of arr[i] is int[10], &arr[i] is int(*)[10], not int*[10] or int*[4]
@Xyand for your info, arr as an expression value is already an int (*)[10]. The syntax &arr[0] is not needed, nor is it needed for any of the other indices, which can be obtained with simply arr + n, each of them int (*)[10]
Just a nit, but you can cast an int[4][10] to int *[4]; a reinterpret_cast will do that nicely. You can't do anything with the results of the cast except to cast it back, of course---it doesn't miraculously change the layout of what is pointed to in memory. But the cast itself is legal and well defined.
@Nawaz I've used it a couple of times, always in machine dependent code. Implementing a stack walk back, for example (which obviously depends on the compiler and the machine architecture).
|
2

note that "int* a[4]" has only 4 pointer to int,Otherwise it can indicate 4 int array,but int "a[4][10]" has 40 integer data type.
so you can not cast it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.