Virozz
Virozz

Reputation: 79

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

Upvotes: 0

Views: 105

Answers (3)

user7664179
user7664179

Reputation:

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

Upvotes: 1

Subodh Vashistha
Subodh Vashistha

Reputation: 1

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; 
} 

Upvotes: 0

eerorika
eerorika

Reputation: 238311

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.

Upvotes: 2

Related Questions