简体   繁体   中英

Array pointer c++

Hello i would like to find out how its doing. I have code like that:

int tab[] = {1,2,3};
int* p;
p = tab; 

cout <<p<<endl; //  cout adress here 
cout <<p[0]<<endl; //  cout first element of the array 

How its doing that p is storing address of first element but p[0] is already storing first element? its working like p[0] = *p ? and p[1] is working like p[1] = *(p+1) ? I know how to use it but I'm little confused because i don't really understand it

How its doing that p is storing address of first element

p is a pointer. A pointer stores an address.

but p[0] is already storing first element?

p[0] is an an element of the array. It stores an integer.

It is possible for a program to store both of these at the same time.

its working like p[0] = *p? and p[1] is working like p[1] = *(p+1)?

Correct. This is how the subscript operator works on pointer and integer.

How its doing that p is storing address of first element

The data type int tab[] is the same as int* , so does the type of p . So both these variables point to the same memory location, and that will be the start of the array.

but p[0] is already storing first element?

Variable tab contains a pointer to the first element of tab[0] , so assigning the same value to another variable will have an equivalent effect.

its working like p[0] = *p? and p[1] is working like p[1] = *(p+1) ?

Yes, *(p+i) is same as p[i] .

If you need a detailed explanation please check this link

Pointer p points to the first variable of an array and as the array has a contiguous allocation of memory, so on *(p+1) it starts pointing to the second variable of the array. You can understand this by further example.

#include <iostream> 
using namespace std; 
int main() 
{ 
    // Pointer to an integer 
    int *p;  
      
    // Pointer to an array of 5 integers 
    int (*ptr)[5];  
    int arr[5]; 
      
    // Points to 0th element of the arr. 
    p = arr; 
      
    // Points to the whole array arr. 
    ptr = &arr;  
      
    cout << "p =" << p <<", ptr = "<< ptr<< endl; 
    p++;  
    ptr++; 
    cout << "p =" << p <<", ptr = "<< ptr<< endl; 
      
    return 0; 
} 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM