Hello ,

I wanted to ask why this works?

int *p = new int[ 1 ];

for ( int i = 0; i < 5; i++ )
{
    p[i] = i;
}

for ( int i = 0; i < 5; i++ )
{
    p[ i ] = 2 * p[ i ];
    cout << "\n" << p[i] << endl; 
}

Since ,we have allocated only for 1 element!

Also , if I have something like this:

typedef struct { 

  int v;
  int arr[ 5 ]; 

} mystruct; 

mystruct * str = new mystruct[ 2 ];

and try to access:

for (int i = 0; i < 7; i++ )
{
    a[ i ] = str[ i ].arr[ 0 ];
}

is it possible?Is it ok?

Because I allocated 2 elemnts of the struce and I am scanning 7.

Recommended Answers

All 4 Replies

You are playing with undefined behavior. You should never go past the end of an array. Just because it worked doesn't mean it will always work. What you actually did was to write data into memory that p has no control over. The compiler does not check these conditions for you. This is why most people will say to use a std::array or std::vector that have at() member that check to make sure you are in bounds.

Ok , thank you.

Regarding the structure?

In order to have this loop:

for (int i = 0; i < 7; i++ )
{
a[ i ] = str[ i ].arr[ 0 ];
}

I must declare:

mystruct * str = new mystruct[ 7 ];

Yes.

Ok , thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.