array question

why does this work, also I didn't reserved the memory?

#include <iostream.h>
using namespace std;
int main()
{
int a[1];
a[0]=1;
a[1]=2;
a[2]=3;
for (int c=0; c<=2; c++)
{
cout<<a[c];
}
}

So what is the difference between array and vector then?
A array is a pointer to a space in memory. When you dont declare an array first as a[3], this memoryspace is not reserved.
However, it can be used to store data in and get data from, just like you do above. You can imagine in bigger applications this causes problems, since the same memoryspace will be used twice.

(You can use the #format when uploading code)
Are you shure that this code is ok, you sould get an error.
When I run it, the output is right but after terminating the program I get this error:
Run-Time Check Failure #2 - Stack around the variable 'a' was corrupted.

I think that using extra items in arrays is not much good
Last edited on
Accessing beyond the end of array a stomps part of the program stack. Since arrays grow upwards in memory and stack typically grows downward, this stomps already allocated stack space.
Yeah the way you usually want to declare an array is to put down how many units in size the array will be (int x[a number here]), and then state the content of each unit on one line (int x[number] = {10, 9, ...}).
Topic archived. No new replies allowed.