I am trying to pass a 2-d array to a function which accept a pointer to pointer. And I have learnt that a 2-d array is nothing a pointer to pointer(pointer to 1-D array). I when I compile the below code I got this error.
#include<iostream>
void myFuntion(int **array)
{
}
int main()
{
int array[][]= {{1,2,3,4},{5,6,7,8,9},{10,11,12,13}};
myFuntion(array);
return 0;
}
In function ‘int main()’:
Line 5: error: declaration of ‘array’ as multidimensional array must have bounds for all dimensions except the first
compilation terminated due to -Wfatal-errors.
Can anybody clear my doubt regarding this and some docs if possible for my more doubts.
asked Oct 20, 2012 at 16:45
9
void myFunction(int arr[][4])
you can put any number in the first [] but the compiler will ignore it. When passing a vector as parameter you must specify all dimensions but the first one.
answered Oct 20, 2012 at 20:59
vmpvmp
2,3721 gold badge13 silver badges16 bronze badges
You should at least specify the size of your second dimension.
int array[][5] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8, 9 }, { 10, 11, 12, 13 } };
There is also an error which is often repeated. To pass a 2D array as argument, you have to use the following types:
void myFuntion(int (*array)[SIZE2]);
/* or */
void myFuntion(int array[SIZE1][SIZE2]);
answered Oct 20, 2012 at 16:59
md5md5
23.3k3 gold badges44 silver badges93 bronze badges
4
Why don’t use std::vector instead of «raw» arrays. Advantages:
1. It can dynamically grow.
2. There is no issues about passing arguments to the function. I.e. try to call void myFuntion(int array[SIZE1][SIZE2]); with array, that has some different sizes not SIZE1 and SIZE2
answered Oct 20, 2012 at 17:02
zabuluszabulus
2,3033 gold badges15 silver badges27 bronze badges
Another templated solution would be:
template<int M, int N>
void myFunction(int array[N][M])
{
}
answered Mar 6, 2019 at 17:41
Matthieu BrucherMatthieu Brucher
21.2k7 gold badges37 silver badges59 bronze badges
#include<iostream>
void myFuntion(int arr[3][4]);
int main()
{
int array[3][4]= {{1,2,3,4},{5,6,7,8},{10,11,12,13}};
myFuntion(array);
return 0;
}
void myFuntion(int arr[3][4])
{
}
http://liveworkspace.org/code/0ae51e7f931c39e4f54b1ca36441de4e
answered Oct 20, 2012 at 17:02
Fatima ZohraFatima Zohra
2,8692 gold badges16 silver badges16 bronze badges
declaration of ‘array’ as multidimensional array must have bounds for all dimensions except the first
So you have to give
array[][size] //here you must to give size for 2nd or more
For passing the array in function , array is not a pointer to a pointer but it’s pointer to an array so you write like this
fun(int (*array)[])
Here if you miss the parenthesis around (*array) then it will be an array of pointers
because of precedence of operators [] has higher precedence to *
answered Oct 20, 2012 at 17:10
OmkantOmkant
8,9008 gold badges38 silver badges58 bronze badges
kuraiMuko 2 / 2 / 0 Регистрация: 11.01.2012 Сообщений: 32 |
||||
1 |
||||
Ошибка в функции(двумерный массив)01.02.2012, 00:00. Показов 10933. Ответов 2 Метки нет (Все метки)
Доброй ночи помогите пожалуйста:
Ошибка в функции:
__________________
0 |
Псевдослучайный 1946 / 1145 / 98 Регистрация: 13.09.2011 Сообщений: 3,215 |
|
01.02.2012, 00:03 |
2 |
Он тебе намекает, что при такой передаче надо указывать размерность(можно кроме первой)
0 |
2 / 2 / 0 Регистрация: 11.01.2012 Сообщений: 32 |
|
01.02.2012, 00:06 [ТС] |
3 |
Спасибо, вопрос закрыт.
0 |
Этот следующий код не компилируется:
int main() {
int a[][] = { { 0, 1 },
{ 2, 3 } };
}
Сообщение об ошибке
error: declaration of 'a' as multidimensional array must have bounds for all dimensions except the first
int a[][] = { { 0, 1 },
^
Это указано стандартом? Если так, то почему? Я думаю, что определить границы здесь было бы очень легко.
1
Решение
Это указано стандартом?
Ну, да.
§8.3.4 / 3 Когда несколько «массивов» спецификаций являются смежными,
создан тип многомерного массива; только первая из констант
выражения, которые определяют границы массивов, могут быть опущены. В
дополнение к объявлениям, в которых используется неполный тип объекта
разрешено, граница массива может быть опущена в некоторых случаях в
объявление параметра функции (8.3.5). Связанный массив может также
быть опущено, когда за декларатором следует инициализатор (8.5).
В этом случае оценка рассчитывается из числа начальных
элементы (скажем,N
) (8.5.1) и тип идентификатора
изD
это «массивN
T
». Кроме того, если есть предшествующее
объявление объекта в той же области, в которой
указан, граница пропущенного массива принимается такой же, как в
более раннее объявление, и аналогично для определения статических данных
член класса.
Если так, то почему?
С одной стороны, массив не может быть построен из неполного типа (void
например). Массив неизвестной границы является одним из тех неполных типов:
§8.3.4 / 1 … Объект типа массива содержит непрерывно распределенный
непустой наборN
подобъекты типаT
, За исключением случаев, указанных ниже, если
константное выражение опущено, тип идентификатораD
является » производный описатель типа-лист массив неизвестных границT
»,
неполный тип объекта. …§8.3.4 / 2 Массив может быть построен из одного из основных типов
(Кромеvoid
), из указателя, из указателя на член, из
класс из типа перечисления или из другого массива.
Более того:
§3.9 Класс, который был объявлен, но не определен, перечисление
введите в определенных контекстах (7.2), или массив неизвестного размера или
неполный тип элемента, является не полностью определенный объект
тип.45 …45) Размер и расположение экземпляра не полностью определенного
тип объекта неизвестен.
Я думаю, что определить границы здесь было бы очень легко.
Новички часто допускают ошибку, заключающуюся в том, что компилятор обладает магическими способностями. Компилятор работает с информацией это уже имеет, это не Создайте информация из воздуха. Если вы попросите его создать объект неизвестного размера, он просто не сможет это сделать. Смотрите следующие примеры:
Только самое внутреннее измерение может быть опущено. Размер элементов в
массив выводится для типа, заданного переменной массива.
Поэтому тип элементов должен иметь известный размер.
char a[] = { ... };
имеет элементы (например,a[0]
) размера 1 (8 бит) и имеет неизвестный размер.char a[6] = { ... };
имеет элементы размера 1 и имеет размер 6.char a[][6] = { ... };
имеет элементы (например,a[0]
, который является массивом) размера 6, и имеет неизвестный размер.char a[10][6] = { ... };
имеет элементы размера 6. и имеет размер 60.Не положено:
char a[10][] = { ... };
будет иметь 10 элементов неизвестного размера.char a[][] = { ... };
будет иметь неизвестное количество элементов неизвестного размера.
Источник
3
Другие решения
Других решений пока нет …
- Forum
- Beginners
- Code wont compile
Code wont compile
I’m getting an error:
|
|
I dont see how that is because I have a size declared in the second []. Here my code:
|
|
Lol, declarations of that type are interpretted back to front.
int array[5] would be a pointer to the first int of five.
int array[5][10] would be a pointer to the first integer array with length 10, of five integer arrays.
Think of it as if it had parentheses around it:
(tests [] ) [MAX_TESTS];
In fact, parentheses wouldn’t be illegal (nor is the whitespace); the compiler should see it the same way.
Say what?
Topic archived. No new replies allowed.
17 Years Ago
Hi, I having this error and i don’t know how to fix it, can anybody help please:
«declaration of `c’ as multidimensional array must have bounds for all dimensions except the first», i’m getting this error because of :
void lcs::LCS_Length(int X[], int Y[], int c[][], char b[][], int m, int n)
{
for( int i = 1; i < m; i++)
c[i][0] = 0;
for( int j = 1; j < n; j++)
c[0][j] = 0;
for( int i = 1; i < m; i++)
for( int j = 1; j < n; j++)
{
if( X[i] == Y[j])
{
c[i][j] = c[i - 1][j - 1] + 1;
b[i][j] = 'D';
}
else if(c[i - 1][j] >= c[i][j - 1])
{
c[i][j] = c[i - 1][j];
b[i][j] = 'U';
}
else
{
c[i][j] = c[i][j - 1];
b[i][j] = 'L';
}
}
}
<< moderator edit: added [code][/code] tags >>
Recommended Answers
You can omit the array size for the first dimension because array names are almost always converted to a pointer to the first element, so any size information is lost. That feature only applies to the first dimension, so you have to provide size information for the second dimension because …
Jump to Post
int a[10][10];
is same as,
int(*a)[10];
Err, NO.
The first, a is an array of 10 arrays of 10 integers.
The second a is a pointer to an array of 10 integers.
Assuming the first,
int a[10][10];
, then the expressiona
evaulates to a typeint(*)[10];
.Which is …
Jump to Post
All 8 Replies
17 Years Ago
I find the diagnostic message quite self-explanitory.
declaration of `c’ as multidimensional array must have bounds for all dimensions except the first
You can’t do [][]. You can do [][5], for example.
Dogtree
23
Posting Whiz in Training
17 Years Ago
You can omit the array size for the first dimension because array names are almost always converted to a pointer to the first element, so any size information is lost. That feature only applies to the first dimension, so you have to provide size information for the second dimension because the conversion to a pointer makes it a pointer to an array of N. These two function declarations are equivalent:
void foo(int a[][10]);
void bar(int (*a)[10]);
To avoid those errors, you can always provide sizes for all dimensions until you’re comfortable with the rules. However, for arbitrary sizes in all dimensions, you have no choice but to use a dynamic array:
void foo(int **a, int m, int n);
int main()
{
int **a = new int*[5];
for (int i = 0; i < 5; i++)
a[i] = new int[5];
foo(a, 5, 5);
for (int i = 0; i < 5; i++)
delete [] a[i];
delete [] a;
}
Of course, that’s assuming you don’t have libraries to work with. The standard vector class is well suited to this:
#include <vector>
void foo(std::vector<std::vector<int> > a);
The boost library also supports a multi_array class.
I_m_rude
10 Years Ago
hey, There is a very huge confusion in my mind for the representation of arrays.
int a[10][10];
is same as,
int(*a)[10];
which means a pointer to an array of 10 intergers. right ?
If yes, then how these statements are correct ?
*(*(a+1)+1)
or,
*(*(a+2)+1)
these statements give correct answers. But, Here it is 2 times dereferecing operator is used which means a is not a pointer to an array of 10, rather it is a pointer to a pointer. I hope i am making my question very clear. please help in this.
thanks in advance.
Edited
10 Years Ago
by I_m_rude
Banfa
597
Posting Pro
Featured Poster
10 Years Ago
int a[10][10];
is same as,
int(*a)[10];
Err, NO.
The first, a is an array of 10 arrays of 10 integers.
The second a is a pointer to an array of 10 integers.
Assuming the first, int a[10][10];
, then the expression a
evaulates to a type int(*)[10];
.
Which is the same type as a in the second case.
So then break down the statment `((a+1)+1)’
a is a pointer to an array of 10 ints
a+1 increments a, the compiler knows the size of a so it increments it by that size to the next array of 10 ints in the array
(a+1) converts us from a pointer to an array of 10 ints to an array of 10 ints which evaluates to a type int *
*(a+1)+1 increments our int * point to the next one in the array
*((a+1)+1) converts out int * to an int
Basically giving the second integer in the second array of 10 ints, functionally equivilent to a[1][1]
.
I_m_rude
10 Years Ago
hey,
You make me clear at one step amd again confused me in another step.
a+1 means pointer to next array of 10 integers. it is ok.
then *(a+1) means the value of (a+1), which is the array of 10 integers. it is ok.
So, now we have array in our hands,
then just doing *(a+1)+1 will give the second element of array. So, you got my confusion i think.
Making myself more clear,
if
*(a+1)+1
give us the second element, then why we again derefercning it using «*» ? i hope i am clear in my question.
thanks. waiting for reply.
Edited
10 Years Ago
by I_m_rude
deceptikon
1,790
Code Sniper
Administrator
Featured Poster
10 Years Ago
This may help. It’s written by Chris Torek, who’s a man deserving of great respect due to his deep knowledge of C.
I_m_rude
10 Years Ago
@decptikon he is really a great person I think. I never heard of him, But If he is a man for having great respect, then you are also not less than that.
The link is simply awesome.
Any other link can you provide for making my concepts more and mpre clear. please please sir!
deceptikon
1,790
Code Sniper
Administrator
Featured Poster
10 Years Ago
Any other link can you provide for making my concepts more and mpre clear.
This one is mostly about data structures and algorithms, but there’s also a reasonably good article on pointers which includes mention of how they relate to arrays.
I don’t doubt I could come up with more links, but my memory works more along the lines of hearing a specific question or comment and thinking «oh, I read an article about that» as opposed to just randomly thinking of something cool or useful.
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Hi,
I am using gcc 4.5.3, which provides the error «multidimensional array
must have bounds for all dimensions except the first» if I try to define
an array type like…typedef int array_t[][];
void test(array_t& arg);
[snip]
My question is this: have I simply managed to temporarily confuse the
compiler, or is there some (maybe obscure) part of the language that
allows multidimensional arrays with unknown bounds in some way?
[snip]
Hi Andy,
I think this thread:
http://thread.gmane.org/gmane.comp.lib.boost.devel/217742
may be talking about what you want. In addition to Pierre-Andre’s
implementation, there’s an alternative implementation mentioned
in another post in that thread:
http://article.gmane.org/gmane.comp.lib.boost.devel/218623
In that alternative implementation, the array_dyn template just
has one template parameter; hence, in your example, the
function prototype would be:
void test(array_dyn<int>& arg);
The actual sizes of each dimension is determined at run-time
by arguments to the templated CTOR:
template<typename T>
template<typename… Size>
struct array_dyn{
…
array_dyn(Size… sizes);
…
};
The downside of the array_dyn implmentation is that accessing
the elements is done with the expression:
arg(i1,i2,…,iN)
where N is the sizeof…(Size), where Size is the template
argument to the CTOR, and that expression requires N
multiplications and N-1 additions.
However, the implementation could be modified to alleviate
this problem using some of the methods described in the
Budd reference:
http://web.engr.oregonstate.edu/~budd/Books/aplc/
that was mentioned elsewhere in that thread.
Another downside is the use of variadic templates. Of course
it would be easy to simply substitute:
std::vector<unsigned>
for:
Size…
if you don’t have a variadic template compiler.
HTH.
-regards,
Larry