Array pointer allocation?

Referring to the comment line:

  • Why does adding parentheses in the example work to print the entire contents of the array?

The example prints β€œone,” then prints the garbage.

#include <iostream>

int main() {
    const char* a[3] = { "one", "two", "three" };
    const char*(*p)[3] = &a;
    for(int i = 0; i < 3; i++) {
        std::cout << *p[i] << std::endl; // this line
    }
    return 0;
}

It works after the change:

std::cout << (*p)[i] << std::endl;
+5
source share
4 answers

p is a pointer to an array of three elements, such as:

β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”
β”‚     β”‚     β”‚     β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜
   ^
   └─ p

Note that it points to the entire array, and not to one of its elements.

The expression is *p[i]considered as *(p[i])due to the priority of the operator (which is equivalent *(*(p + i))). This means that you are indexing a pointer to an array. If you do p[1], for example, you move the pointer to the "next" array and try to dereference it:

β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”
β”‚     β”‚     β”‚     β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜
                     ^
                     └─ p + 1

, , undefined. , (*p)[i] ( *((*p) + i)), , . , . , :

β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”
β”‚     β”‚     β”‚     β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜
   ^
   └─ *p

, . , , (*p)[1], :

β”Œβ”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”
β”‚     β”‚     β”‚     β”‚
β””β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜
         ^
         └─ (*p) + 1

const char*, cout.

+16

. () [] , dereferenced. () - dereference, [].

+6

operator priority .

Array selection has higher priority than dereferencing, so from a compiler point of view, this is valid:

*(p[i])
+2
source
        #include <iostream>
        using namespace std;       

        int main() {


            int arr[5] = {1,2,3,4,5};

            int *p=arr;


            int intgerSize=sizeof(int);


            for(int k=0;k<5;k++)


            {  
                cout<<"arr ["<<k<<"] "<<*(p+(k*sizeof(int)/intgerSize));  
                cout<<"  "<<(p+(k*sizeof(int)/intgerSize));
                cout<<"  "<<p+k<<"\n"; 

            }`enter code here`

            return 0;
        }
OUTPUT:- 
arr [0] 1 0x7ffd180f5800  0x7ffd180f5800
arr [1] 2 0x7ffd180f5804  0x7ffd180f5804
arr [2] 3 0x7ffd180f5808  0x7ffd180f5808
arr [3] 4 0x7ffd180f580c  0x7ffd180f580c
arr [4] 5 0x7ffd180f5810  0x7ffd180f5810
+1
source

All Articles