- Forum
- Beginners
- Size of array too large
Size of array too large
Hello! I am writing a small program and I need an array that contains 1.000.000.000 numbers. When I compile it, I get the error «size of array ‘v’ is too large.» What is the maximum limit of elements an array can store?
OS: Windows 8.1 32 bit
IDE:CodeBlocks
«v» is an int
Compiler is GNU gcc
Thanks in advance!
First of all, it depends on environment. 32-bit OS allows less memory for an application than a 64-bit OS.
Second, you don’t say what kind of array you are using, so I presume a plain statically allocated local array.
Local variables are in stack memory, which is quite limited.
Dynamic allocation uses free memory area. Try to use std::vector
Look at «size_type» in http://www.cplusplus.com/reference/array/array/
Then look at http://www.cplusplus.com/reference/limits/numeric_limits/
With those you can test some limits on your environment.
Try this code:
|
|
You are allocating 1 billion numbers. If those numbers are integers, then they are probably 4 bytes long. You’re running a 32 bit operating system which means that a process is limited to 4GB total (probably less: the OS usually reserves part of the address space for various other things).
Bottom line: you can’t allocate a 4GB array when have only 4GB for the entire process.
What are you doing with the array? Chances are excellent that with a little thought, you’ll find that you don’t actually need to store all of the numbers simultaneously.
Topic archived. No new replies allowed.
Тут думаю важно как реализован вывод в библиотеке, Вы какую используете, есть там примеры вывода изображений?
Для экранчика от нокии1202 массив выглядит так например, но это просто пример, для Вас нужно смотреть библиотеку.
static const char image_gres[768] PROGMEM = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x83, 0x7D, 0x5D, 0x9B, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0xED, 0xED, 0x13, 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x6D, 0x6D, 0x7D, 0xFF, 0xFF, 0xFF, 0xFF, 0xB3, 0x6D, 0x6D, 0x9B, 0xFF, 0xFF, 0xFF, 0xFF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remove From My Forums
-
Question
-
Hi,
I am having difficulty with arrays because of the limitation of the size of the arrays that I can declare.
I need sizes that are very large and windows or C# does not allow me to create bigger than the following for example:public static int[] gaPoints = new int[20000000000000000000 + 1];
I get an error message saying that «integral size is too large».
I need to be able to declare sizes that are even much larger than the abovementioned size.
How can I circumvent this problem?
Do I have to use something other than arrays?
TIA
Roy
Answers
-
-
Proposed as answer by
Tuesday, March 26, 2013 2:35 AM
-
Marked as answer by
Mike Feng
Wednesday, April 3, 2013 4:54 PM
-
Proposed as answer by
-
You may need to rethink this a little bit. Your sample array (I love the +1 in the size by the way) is 80 ExaBytes in size (plus 4 bytes). The ram for this computer will cost you about 20 billion dollars (I’m assuming that you get a large discount
on a purchase of this size). I don’t think your computer will have enough slots to hold the memory cards! If you can read one int every nanosecond it will take about 600 years to iterate through the array.As I say, you might want to rethink your approach to this problem.
Paul Linton
-
Proposed as answer by
Mike Feng
Tuesday, March 26, 2013 2:38 AM -
Marked as answer by
Mike Feng
Wednesday, April 3, 2013 4:54 PM
-
Proposed as answer by
I need a large 3D array of structures:
struct s {
char a[40];
int b;
};
s s_array[10000][10000][100];
s_array is declared as global.
Unfortunatelly, when compiling, I get an error: «size of array
‘s_array’ is too large»
(using GCC, but I think it doesn’t matter)
But I have read, that global variables can be very large. Is it true?
And how can I make it in other way?
Thank you for answers.
Mar 21 ’06
#1
* ultr:
I need a large 3D array of structures:
struct s {
char a[40];
int b;
};
s s_array[10000][10000][100];s_array is declared as global.
Unfortunatelly, when compiling, I get an error: «size of array
‘s_array’ is too large»
(using GCC, but I think it doesn’t matter)
Try to compute the size of your array assuming s is 42 bytes.Hint: when you multiply by 10, just add a zero at the end of the number.
But I have read, that global variables can be very large. Is it true?
Yes.And how can I make it in other way?
Smaller, or, wait a few years.
—
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Mar 21 ’06
#2
ultr wrote:
I need a large 3D array of structures:
struct s {
char a[40];
int b;
};
s s_array[10000][10000][100];s_array is declared as global.
Unfortunatelly, when compiling, I get an error: «size of array
‘s_array’ is too large»
(using GCC, but I think it doesn’t matter)But I have read, that global variables can be very large. Is it true?
And how can I make it in other way?
You can allocate static storage for variables, and it can generally be
larger since it’s not allocated <ot>on the stack</ot> like automatic
variables. You could also use dynamic memory allocation (new/delete or
malloc/free) to achieve the same goal.
However, your array *is* very large, and on a typical 32-bit system it
would be (10^10)*(40+4) = 440000000000 = 0x66720B3000 which is well
beyond 32-bit pointer ranges. (Are you writing exclusively for 64-bit
machines or better?)
You could solve this problem in any number of ways. One is to access
the array in chunks so you only use part of that memory at any one
time. Another would be to break up your array behind some abstraction.
Etc. Etc. Give us a better idea of what you’re doing, and perhaps we
can make some better suggestions.
Cheers! —M
Mar 21 ’06
#3
ultr wrote:
I need a large 3D array of structures:
struct s {
char a[40];
int b;
};
s s_array[10000][10000][100];s_array is declared as global.
Unfortunatelly, when compiling, I get an error: «size of array
‘s_array’ is too large»
(using GCC, but I think it doesn’t matter)But I have read, that global variables can be very large. Is it true?
And how can I make it in other way?Thank you for answers.
Think about how much space you’re asking for. sizeof(s) is at least 40
(more actually, but I like round numbers). s_array has 10000 * 10000 *
100 = 10^10 elements. So you’re asking for at least 400GB of memory. I
think you need more RAM or a better algorithm.
Mar 21 ’06
#4
ultr wrote:
I need a large 3D array of structures:
struct s {
char a[40];
int b;
};
s s_array[10000][10000][100];s_array is declared as global.
Unfortunatelly, when compiling, I get an error: «size of array
‘s_array’ is too large»
(using GCC, but I think it doesn’t matter)
Do you actually have enough memory? Do you have a 64 bit platform. 32 bit
ones usually can only handle memory blocks of up to 4 GB size, which is by
far not enough for your array.
But I have read, that global variables can be very large. Is it true?
And how can I make it in other way?
Instead of holding hundreds of gigabytes in memory, you should have them on
disk and only load the parts currently needed. You probably need some
clever caching.
Mar 21 ’06
#5
ultr wrote:
I need a large 3D array of structures:
struct s {
char a[40];
int b;
};
s s_array[10000][10000][100];
<snip>
If your data is sparse, you could use a map instead of an array.
Best regards, JE
Mar 21 ’06
#6
Instead of holding hundreds of gigabytes in memory, you should have them
on
disk and only load the parts currently needed. You probably need some
clever caching.
I don’t think most of us even _have_ over 400gig of hard drive space.
Drives that big are pretty new, aren’t they? (I’d suggest he find another
solution entirely.)
-Howard
Mar 22 ’06
#7
Howard wrote:
Instead of holding hundreds of gigabytes in memory, you should have them
on
disk and only load the parts currently needed. You probably need some
clever caching.I don’t think most of us even _have_ over 400gig of hard drive space.
Drives that big are pretty new, aren’t they? (I’d suggest he find another
solution entirely.)
You never know, he might be running on a SunFire server with 570Gb of RAM…
—
Ian Collins.
Mar 22 ’06
#8
This discussion thread is closed
Replies have been disabled for this discussion.
Заблокирован |
||||
1 |
||||
29.11.2013, 12:02. Показов 9262. Ответов 28 Метки нет (Все метки)
Ну собственно Visual Studio 2012, платформа x64, при попытке создать массив из 10-и миллиардов элементов
получаю резонный error:
0 |
zss Модератор 12644 / 10136 / 6104 Регистрация: 18.12.2011 Сообщений: 27,173 |
||||
29.11.2013, 12:13 |
2 |
|||
Создайте двумерный массив,
0 |
Заблокирован |
|
29.11.2013, 12:22 [ТС] |
3 |
Создайте двумерный массив, не ну это то понятно, можно и два отдельных массива создать, но хотелось бы иметь один выровненный в памяти массив, и чтоб потом читать из него по правилам memory coalescing С чем вообще связанно это ограничение? Неужели нет каких то вариантов массивов с бОльшим числом элементов?
0 |
Модератор 12644 / 10136 / 6104 Регистрация: 18.12.2011 Сообщений: 27,173 |
|
29.11.2013, 12:40 |
4 |
Из программы Вы используете 64 разрядный указатель.
0 |
Заблокирован |
|
29.11.2013, 12:47 [ТС] |
5 |
з программы Вы используете 64 разрядный указатель. это ещё почему? вот это 0x7fffffff — это 32-х разрядное число, в 64- битных платформах адреса выглядят так — см картинку (то есть в два раза больше) Миниатюры
0 |
Модератор 12644 / 10136 / 6104 Регистрация: 18.12.2011 Сообщений: 27,173 |
|
29.11.2013, 13:01 |
6 |
Пардон, оговорился (имел ввиду 32-разрядный адрес).
0 |
Заблокирован |
|
29.11.2013, 13:11 [ТС] |
7 |
В VS для этого надо создать соответствующий проект. )))) какой ещё проект ? смотрите на скрине — конфигурация 64-х битная стоит.
0 |
Модератор 12644 / 10136 / 6104 Регистрация: 18.12.2011 Сообщений: 27,173 |
|
29.11.2013, 13:26 |
8 |
То, что у Вашего компьютера 64 разрядная платформа не означает,
0 |
Заблокирован |
|
29.11.2013, 13:45 [ТС] |
9 |
Хотя, я в VS2012 не работал. Может она автоматически решает, что в студии ты как бы создаёшь 64-х битную конфигуруцию — и можешь быть уверен, что больше для этого ничего не надо, т.к. исходя из скрина ваше — адреса у меня 64-х битные (могу ещё регистры RAX привести, если не веришь)
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
29.11.2013, 13:46 |
10 |
С чем вообще связанно это ограничение? Неужели нет каких то вариантов массивов с бОльшим числом элементов? Посчитали сколько памяти нужно на такой массив?
0 |
Don’t worry, be happy 17784 / 10550 / 2036 Регистрация: 27.09.2012 Сообщений: 26,536 Записей в блоге: 1 |
|
29.11.2013, 13:47 |
11 |
Посчитали сколько памяти нужно на такой массив? конечно:
не надо спрашивать, сколько у меня оперативной памяти — достаточно.
0 |
858 / 447 / 112 Регистрация: 06.07.2013 Сообщений: 1,495 |
|
29.11.2013, 13:53 |
12 |
Посчитали сколько памяти нужно на такой массив? ну 80 гигов то есть примерно?
error C2148: total size of array must not exceed 0x7fffffff bytes не из той серии когда не хватает памяти
0 |
alsav22 5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
||||
29.11.2013, 13:58 |
13 |
|||
2 |
Заблокирован |
|
29.11.2013, 13:58 [ТС] |
14 |
не из той серии когда не хватает памяти да причём тут память? Эта ошибка при компиляции вылетает ))0 Не в рантайме же
0 |
Ryuk |
29.11.2013, 14:02
|
Не по теме: newbie666, супер-игру создаешь?
0 |
Заблокирован |
|
29.11.2013, 14:08 [ТС] |
16 |
newbie666, супер-игру создаешь? систему искусственного разума с управляемыми ей подмодулями распознавания/ синтеза речи, компьютерного зрения и тд и тп
0 |
3986 / 3255 / 910 Регистрация: 25.03.2012 Сообщений: 12,114 Записей в блоге: 1 |
|
29.11.2013, 14:11 |
17 |
Компилируешь в режиме x86 или х64? Имхо, пока не запустил в рантайме, все равно, сколько у тебя оперативки!
0 |
5493 / 4888 / 831 Регистрация: 04.06.2011 Сообщений: 13,587 |
|
29.11.2013, 14:13 |
18 |
newbie666, что молчишь? Если как в 13 посте сделать, компилируется?
1 |
Заблокирован |
|
29.11.2013, 14:26 [ТС] |
19 |
Компилируешь в режиме x86 или х64? да посмотри пост ёлки палки Можно ли обойти ограничение на максимальный размер массива ? error C2148: total size of array must not exceed 0x7fffffff bytes
newbie666, что молчишь? Если как в 13 посте сделать, компилируется? ААААААААА вот я баран конечно компилируется :-))))))))))) unsigned long long n = 10000000000; если тут вручную вбить вместо n число — тогда не компильнётся, я совсем забыл, что любое целое число по умолчанию приводится к инту )))))))) а она современных ОС — он 32-х битовый ))) Тоесть компилятор вручную заданное число приводил к инту и охреневал, что я очень большое число влепил))))) СПАСИБО ЧТО ВПРАВИЛИ МНЕ МОЗГ )))
1 |
0 / 0 / 0 Регистрация: 15.04.2014 Сообщений: 9 |
|
16.04.2014, 00:53 |
20 |
систему искусственного разума с управляемыми ей подмодулями распознавания/ синтеза речи, компьютерного зрения и тд и тп
unsigned long long n = 10000000000; компилируется, но exception bad allocation…. как быть? Добавлено через 6 минут
0 |