+ 1
What is the difference between &arr and arr and how does the following works ?
const char *arr[] = {"C", "C++", "Java", "VBA"}; const char *(*ptr)[4] = &arr; cout << (*ptr)[2]; What i understand is that &arr holds the address of the whole arr while arr holds the address of first value of arr. But i can't understand what is the following line doing , *(*ptr)[4] = &arr , is it a way to declare a pointer to whole array just like "*ptr=arr" will declare pointer to first value of array"! Ty !
2 Antworten
+ 1
Martin Taylor thanks a lot !
+ 1
The old C declaration syntax was designed to mimic the USE of the declared thing.
So,
const char *(*ptr)[4];
declares `ptr` to be used as follows:
1. Dereference it, `*ptr`.
2. That yields something A that can be indexed, A[4].
3. The result of the indexing is a `const char*`.
This means that (1) `ptr` is a pointer, to (2) an array of four (3) `const char*` pointers.
--
You can tidy up such declarations by NAMING things. For example, introduce the name
using C_str = const char*;
Then you can write
C_str (*ptr)[4];
There's still that nested `ptr` though. A bit hard to grok until one gets fully familiar with the pattern. You can be more C++'ish by defining a general TYPE BUILDER like this:
template< class T > using Type_ = T;
Then you can write
Type_<C_str[4]>* ptr;
This hoists out the name `ptr` to the usual position of a name in a declaration, because the type builder supports general substitution in type expressions. The old C syntax does not, in contrast to most every other programming lang.