pointers, arrays and elements...

Hello!
Please, in first function I created array a.
Function is returning POINTER of the array a.
In main, variable z is a pointer. But , is z an array.- or not?

If it is, I do not see where I have declared it as an array???
If z is NOT an array, how can we get vales for its elements(z[0], z[1], z[2])???
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  #include<iostream>
using namespace std;

int* po(int b){
  int d1;
  d1=3*b;
  int d2;
  d2=d1+5;
  int d3;
  d3=d2+3;
  int* a=new int[3];


  //int a[3]={d1,d2,d2+3};

  a[0] = d1;
  a[1] = d2;
  a[2] = d3;


  cout<<"Adress of the array a is: "<<&a[0]<<endl<<endl<<endl;
return a;
}


int main(){
  cout<<"Now main starts"<<endl;
  int st=5;
  int * z;
  z=po(st);

  cout<<endl<<endl;
  cout<<z<<endl<<&z<<endl<<endl;

  cout<<"text1: "<<po(st)<<" TEXT2: "<<endl;
  cout<<z[0]<<" "<<z[1]<<" "<<z[2]<<endl;
  cout<<&z[0]<<" "<<&z[1]<<" "<<&z[2]<<endl;


return 0;
}
 
 



MANY THANS!!!!
z is not an array. It is merely is a pointer to int. Subscript operator is absolute equivalent to the pointer arithmetics. Therefore z[0] == *(z + 0), z[1] == *(z + 1) etc. As you can use pointer arithmetics to access values in continuous memory, you can use subscript operator too.

Actually 1[z] is a valid way to do array subscription. More, following is valid too:
1
2
int array[2][2][2][2] = {};
1[0[array][1]][0] = 1;
Many thanks- right what I thought.
Please, can someone paste a link about subscript operator, pointer arithmetics and array subscription.

I sure understand what U said, but I never met an expression like f.e.

1[z] before. Would be happy to manage this.

Many thanks!
Standard wrote:
5.2.1 Subscripting [expr.sub]

1 A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T” and the other shall have unscoped enumeration or integral type.
The result is an lvalue of type “T.” The type “T” shall be a completely-defined object type.62 The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. —end note]
Last edited on
Topic archived. No new replies allowed.