V
V
Vladislav2016-05-12 19:11:50
C++ / C#
Vladislav, 2016-05-12 19:11:50

Why is it necessary to specify the number of columns?

Why can't a two-dimensional array be passed to a function simply as a pointer
to an array? Why is the second dimension necessary?
So that the compiler allocates memory for a specific array?
Then why can you ignore the first dimension, if
you can write in the arguments like this:
int test(int (*a)[5])
?
*a - this is a call to the address, to the address a , no?
So the name of the array in this context is not the same as the pointer??

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fat Lorrie, 2016-05-12
@Hateman31

In C++, two-dimensional arrays are not implemented at the language level, as is done, for example, in C#. Here we have only a little syntactic sugar, in the form of square brackets.
For example, all these expressions for referring to the third element of the array a are equivalent and will be compiled:
know exactly how long they are (for addressing between rows) - we need to know the number of columns.
In case of dynamic memory allocation

const int ARRAY_SIZE = ...;

int **arr = new int*[ARRAY_SIZE];
for (int rown=0; rown<ARRAY_SIZE; ++rown) {
    arr[rown] = new int[ARRAY_SIZE];
}

мы и вовсе будем иметь дело с массивом указателей на строки, которые разбросаны по памяти стандартным аллокатором.
Таким образом, только МЫ знаем, что эта штука - двумерный массив, а не просто указатель на некоторую область памяти, как об этом думает функция.
Конечно, стоит присмотреться к специальным классам вроде std::vector<T> и std::valarray<T>, на основе которых можно строить что-то вроде std::vector<std::vector<int>>. Эти типы уже не голые указатели и несут в себе свойство size(), с помощью которого мы можем оценивать размерности.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question