How many elements has that array???

Hello!
If U rememebr this program, array a /array z should have 3 elements each.
In first function, these elements are also defined, arne't they?

But, now I just added in main to output one element more- and it did.
So, how many elements does this array have in the end?
MANY THANKS!!!
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
45
46
47
48
49
50
51
  

#include<iostream>
using namespace std;

int* po(int b){
i  nt 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;

  int* arr;
  cout<<"text1: "<<" TTTTTT "<<(arr=po(st))<<" TEXT2: "<<endl;
  cout<<z[0]<<" "<<z[1]<<" "<<z[2]<<" "<<z[3]<<endl;
  cout<<&z[0]<<" "<<&z[1]<<" "<<&z[2]<<" "<<&z[3]<<endl;
  cout<<endl;
  cout<<arr<<" "<<&arr<<endl;

return 0;
}





Array has 3 elements. As I mentioned you before array subscript is a simple pointer arithmetics and dereferencing. C++ does not prevents you from accessing any memory area (it assumes programmer are smart enough to know what he is doing):
1
2
3
4
5
int main()
{
    int* p = (int*)0xDEADBEEF;
    *p = 0;//INSTANT CRASH
}

You are referencing to some uninitializated memory area in main(), so behavior is undefined.
Hello!
I am gettin 17 as the forth element.
It is obvioulsy random isn+t it?
(It surprise me the number is that small!)

I suppose, these places in memory are not "fixly occupied" by new[]
enemy wrote:
It is obvioulsy random isn+t it?
MiiNiPaa wrote:
behavior is undefined.
I would not be surprised if it will transfrorm your PC into killer robot: Standard allows it on out of border access.
Many thanks! Clear now!
Topic archived. No new replies allowed.