0

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.

2
Contributors
4
Replies
15
Views
2 Years
Discussion Span
Last Post by glao
Featured 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 … Read More

1

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.

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.