What is the difference between &arr and arr and how does the following works ? | Sololearn: Learn to code for FREE!

+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 !

9/17/2021 10:41:06 AM

Abhay

4 Answers

New Answer

+3

Your assumption is correct In this example arr is an array of 4 char pointers. Each pointer is pointing to a string. Since the name of an array decays to a pointer the name of an array of pointers will decay to a pointer to a pointer. This is just semantics used by the compiler so that it can treat the variable appropriately. The actual address of the start of the array and the first element are both the same.

+1

Martin Taylor thanks a lot !

+1

If you read it from inside, then move to right and left you'll understand it. From the inside, it shows that (*ptr) is a pointer, moving to the right , it shows that the pointer points to an array of 4 items.. And each of these items are a const char* type. Since ptr is a pointer, it rvalue should be an address which is &arr. i think this same method is used to point to a function. for example bool (*callback)(int, int) - callback is a pointer - pointing to a function that accepts two int argument - it returns a bool

+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.