Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.80/5: Рейтинг темы: голосов - 5, средняя оценка - 4.80
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 11

Полная явная инициализация многомерного массива

11.07.2015, 12:17. Показов 1064. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Помогите дать определение и приведите пример.
Заранее спасибо!
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
11.07.2015, 12:17
Ответы с готовыми решениями:

Инициализация многомерного массива
Помогите заполнить многомерный массив этим массивом ДАЗРВС ТУЕПОМ ЙБГЖИК ЛНФХЦЧ ШЩЪЫЬЭ ЮЯ. ,- (четвёртый символ - это...

JavaScript!? Инициализация многомерного массива?
JavaScript, как правильно инициализировать многомерный массив? // var quest= , ] - это такой массив должен в итоге получиться ...

Инициализация многомерного массива Perl
Добрый день! Помогите с инициализацией многомерного массива perl: (пример взят отсюда:...

3
2549 / 1208 / 358
Регистрация: 30.11.2013
Сообщений: 3,826
11.07.2015, 12:33
C++
1
2
3
4
5
6
7
8
9
10
11
const int width = 10;
    const int height = 3;
    int** ptr = new int*[height];
 
    for(auto y = 0; y < height; y++)
        ptr[y] = new int[width];
 
    int i = 1;
    for(auto y = 0; y < height; y++)
    for(auto x = 0; x < width; x++)
        ptr[y][x] = i++;
1
Эксперт С++
 Аватар для hoggy
8973 / 4319 / 960
Регистрация: 15.11.2014
Сообщений: 9,760
11.07.2015, 13:08
Цитата Сообщение от l2megaboss Посмотреть сообщение
Помогите дать определение и приведите пример.
Заранее спасибо!
определение:

Кликните здесь для просмотра всего текста
8.3.4 Arrays [dcl.array]
1 In a declaration T D where D has the form
D1 [ constant-expressionopt ]
Draft
157 Declarators 8.3 Meaning of declarators
and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T,” then the type of the identifier of
D is an array type. T is called the array element type; this type shall not be a reference type, the (possibly cv-qualified)
type void, a function type or an abstract class type. If the constant-expression (5.19) is present, it shall be an integral
constant expression and its value shall be greater than zero. The constant expression specifies the bound of (number of
elements in) the array. If the value of the constant expression is N, the array has N elements numbered 0 to N-1, and
the type of the identifier of D is “derived-declarator-type-list array of N T.” An object of array type contains a contiguously
allocated non-empty set of N subobjects of type T. If the constant expression is omitted, the type of the identifier of D is
“derived-declarator-type-list array of unknown bound of T,” an incomplete object type. The type “derived-declarator-typelist
array of N T” is a different type from the type “derived-declarator-type-list array of unknown bound of T,” see 3.9. Any
type of the form “cv-qualifier-seq array of N T” is adjusted to “array of N cv-qualifier-seq T,” and similarly for “array of
unknown bound of T.” [ Example:
typedef int A [5] , AA [2][3];
typedef const A CA ; / / type is “array of 5 const int”
typedef const AA CAA ; / / type is “array of 2 array of 3 const int”
— end example ] [Note: an “array of N cv-qualifier-seq T” has cv-qualified type; see 3.9.3. — end note ]
2 An array can be constructed from one of the fundamental types (except void), from a pointer, from a pointer to member,
from a class, from an enumeration type, or from another array.
3 When several “array of” specifications are adjacent, a multidimensional array is created; the constant expressions that
specify the bounds of the arrays can be omitted only for the first member of the sequence. [Note: this elision is useful
for function parameters of array types, and when the array is external and the definition, which allocates storage, is
given elsewhere. — end note ] The first constant-expression can also be omitted when the declarator is followed by an
initializer (8.5). In this case the bound is calculated from the number of initial elements (say, N) supplied (8.5.1), and
the type of the identifier of D is “array of N T.”
4 [ Example:
float fa [17] , * afp [17];
declares an array of float numbers and an array of pointers to float numbers. For another example,
static int x3d [3][5][7];
declares a static three-dimensional array of integers, with rank 3 × 5 × 7. In complete detail, x3d is an array of three
items; each item is an array of five arrays; each of the latter arrays is an array of seven integers. Any of the expressions
x3d, x3d[i], x3d[i][j], x3d[i][j][k] can reasonably appear in an expression. — end example ]
5 [Note: conversions affecting lvalues of array type are described in 4.2. Objects of array types cannot be modified, see
3.10. — end note ]
6 Except where it has been declared for a class (13.5.5), the subscript operator [] is interpreted in such a way that E1[E2]
is identical to *((E1)+(E2)). Because of the conversion rules that apply to +, if E1 is an array and E2 an integer, then
E1[E2] refers to the E2-th member of E1. Therefore, despite its asymmetric appearance, subscripting is a commutative
operation.
7 A consistent rule is followed for multidimensional arrays. If E is an n-dimensional array of rank i × j × ... × k, then
E appearing in an expression is converted to a pointer to an (n − 1)-dimensional array with rank j × ... × k. If the *
Draft
8.3 Meaning of declarators Declarators 158
operator, either explicitly or implicitly as a result of subscripting, is applied to this pointer, the result is the pointed-to
(n−1)-dimensional array, which itself is immediately converted into a pointer.
8 [ Example: consider
int x [3][5];
Here x is a 3 × 5 array of integers. When x appears in an expression, it is converted to a pointer to (the first of three)
five-membered arrays of integers. In the expression x[i] which is equivalent to *(x+i), x is first converted to a pointer
as described; then x+i is converted to the type of x, which involves multiplying i by the length of the object to which
the pointer points, namely five integer objects. The results are added and indirection applied to yield an array (of five
integers), which in turn is converted to a pointer to the first of the integers. If there is another subscript the same argument
applies again; this time the result is an integer. — end example ]
9 [Note: it follows from all this that arrays in C++ are stored row-wise (last subscript varies fastest) and that the first
subscript in the declaration helps determine the amount of storage consumed by an array but plays no other part in
subscript calculations. — end note ]


пример:
C++
1
2
3
4
const char* arr[][3]
{
    "1111", "222", "3333"
};
Цитата Сообщение от rikimaru2013 Посмотреть сообщение
int** ptr = new int*[height];
детонирует непрерывные блоки памяти в куче
и не имеет никакого отношения к массивам языка с++.
2
0 / 0 / 0
Регистрация: 22.02.2015
Сообщений: 11
11.07.2015, 13:50  [ТС]
и все, же помогите дать определение(не такое длинное). как сформулировать попроще?)
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
11.07.2015, 13:50
Помогаю со студенческими работами здесь

Инициализация многомерного массива в одну строчку
Подскажите пожалуйста как можно инициализировать многомерный массив с прописью нужных ключей вот как я делаю сейчасstring question = new...

Нужна полная инициализация для дисплея на базе HD44780.
Имею плату STM32F4 Dyscovery и дисплейчик(WH1601B) на базе HD44780. Сам я новичок, уже всё перепробывал, разные инициализации брал, сам...

Метод конечных разностей. Явная и не явная схема
Помогите пожалуйста методом конечных разностей решить уравнения с заданными начальными и граничными условиями используя явную и неявную...

Явная передача массива в функцию
Подскажите, можно ли в С++ передать в функцию массив таким образом: void f (int* a); int main () { f ({1, 2, 3, 4,...

Внутреннее устройство многомерного массива и неявное преобразование массива в указатель
Букв получилось многовато. Поэтому, чтобы сэкономить Ваше время, предлагаю сразу вопрос: Буду очень благодарен, если кто-то сможет...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru