Is array member defined or not?

1
2
3
4
5
int* a = new int[10];
for(int i=0;i<800;i++){
    a[i]=i;
    std::cout<<a[i]<<'\n';
    }

And it prints 800 numbers on the console.

But why when the part int* a = new int[10]; says that it should be 10 place members, not 800?
When dynamic arrays can do that, what is the size of the array for anyway ([10])?
Last edited on
new int[10];

That number is how many int objects to make space for. That's the memory that is guaranteed to be yours, and not used by anything else. In this case, enough room for 10 integers. The memory after that is not yours. The fact that you can read it and write it does NOT make it part of the array.

a[i]=i;
This means *(a+i) = i;. It is pointer arithmetic and dereferencing a pointer. There is NO check that what that points to is yours. It is up to YOU to make sure that you do not try to read/write memory that isn't yours.

The next 790 spaces that you write to is not your memory. If anything is stored there, you will trash it. If the OS doesn't like you reading that memory, it will segFault.

Welcome to C and C++; you are trusted to know what you are doing, and if you ask to read/write to some memory, it's up to you to know that it's your memory to be reading/writing.
Last edited on
Yea, I don't know "everything" how C++ works, but when I write the code it just does (or I think it does...).

This was odd to me so I asked.
Thanks I understand now.
Topic archived. No new replies allowed.