remlostime said:
now, i write some code
code1:
int a[10000000];
int main(){}
code2:
vector<int> a(10000000);
int main(){}
after using g++ compile, and run it, code1 is broken, but code2 runs
well, why?
i think the size of a is the same in code1 and code2, but only vector
can run big size, how can i
use big size in array?
As others here have noted, your compiler likely isn't
allocating enough global memory to handle Code1.
For information purposes, my favoritie compiler, DJGPP
(DJ Delorie's port of g++ to the 32-bit Windows command-prompt)
compiles and runs those both fine (at least when I put in the
missing headers, the missing "std::", etc).
Oddly, your Code1 takes an exhorbitant amount of time to compile,
about 60 seconds, whereas your Code2 only takes 2 seconds. Unknown
why the extreme difference in compile time. May have something to
do with the necessity of allocating over 40 million bytes of global
memory.
But both version DO compile and run. I get:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code1:
#include <iostream>
int a[10000000];
int main (void)
{
std::cout << "sizeof a = " << sizeof a << std::endl;
return 0;
}
cwd = C:\RHE\src\test
$make a-array-test.exe
Using pattern rule %.exe:%.cpp to compile a-array-test.cpp to a-array-test.exe:
gpp -I c:/rhe/src/test -I C:/RHE/include -Wall -Os -s a-array-test.cpp -LC:/RHE/
lib -lrh -lfl -ly -lm -lname -o C:/bin-test/a-array-test.exe
a-array-test.exe is up to date.
cwd = C:\RHE\src\test
$a-array-test
sizeof a = 40000000
cwd = C:\RHE\src\test
$
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code2:
#include <iostream>
#include <vector>
std::vector<int> a(10000000);
int main (void)
{
std::cout << "sizeof a = " << sizeof a << std::endl;
return 0;
}
cwd = C:\RHE\src\test
$make a-vector-test.exe
Using pattern rule %.exe:%.cpp to compile a-vector-test.cpp to a-vector-test.exe
:
gpp -I c:/rhe/src/test -I C:/RHE/include -Wall -Os -s a-vector-test.cpp -LC:/RHE
/lib -lrh -lfl -ly -lm -lname -o C:/bin-test/a-vector-test.exe
a-vector-test.exe is up to date.
cwd = C:\RHE\src\test
$a-vector-test
sizeof a = 12
cwd = C:\RHE\src\test
$
Note that the array takes up 40MB of global memory, whereas
the vector only takes 12 bytes, with the remainder being
dynamically allocated. So the ways in which Code1 and Code2
use memory are DRASTICALLY different, hence I wouldn't be
surprised at all if they behave differently on some platforms.
I'd strongly recommend the vector version for several reasons:
1. Cleaner-looking code.
2. Less error prone.
3. Built-in range checking available.
4. Memory allocation handled for you.
5. Doesn't strain global memory space as much.
--
Cheers,
Robbie Hatley
lonewolf aatt well dott com
www dott well dott com slant user slant lonewolf slant