Error when passing array to function

Dear All,

Could you please help me with the compiling error of the following code?

prog.cpp:17: error: cannot convert 'float (*)[(((long unsigned int)(((long int)size) + -0x00000000000000001)) + 1)]' to 'float (*)[5]' for argument '1' to 'void f(float (*)[5])'

Thanks in advance,

Paul


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <utility>

using namespace std;

void f(float p[][5])
{
    int i, j;
    
    for (i = 0; i < 2; i++)
        for (j = 0; j < 5; j++)
            p[i][j] = i*j;
}

int main()
{
    int size = 5;
    float p[2][size];
    int i, j;
    
    f(p);
    
    for (i = 0; i < 2; i++)
        for (j = 0; j < 5; j++)
            cout << p[i][j] << " ";
    
    cout << endl;
    
    return 0;
}
Change line 20 to const int size=5;
Arrays of variable size are illegal.

Change the declaration of f() to void f(float p[2][5])
Thanks, Helios! It works!

Suppose now that one wants to define the function like the following:

void f(float p[][size])

Can one get a legal piece of code to do that?

Paul
If you are worrying about the use of multidimensional arrays, there is an article in these forums that discusses their use. I believe you will find some answers to your question there.
Define size as a const integral global variable and you'll be able to use it in the function parameter.
A better approach would be with a template.
Thanks for your answers to my posts! Meanwhile, by using dynamic memory (using an array of pointers to arrays), I was able to overcome the problem. Perhaps, this very technique (using an array of pointers to arrays) can be applied to static memory.

Paul
STL containers could be used rather than arrays. In that case you would not have to explicitly designate the sizes and could traverse the containers using iterators. Both vectors and deques provide random access.

Just make sure to pass it to your function by pointer (or reference), so that it can be modified.
Last edited on
Many thanks again! I will have a look at STL containers. I am still learning C++, coming from C.

Paul
Topic archived. No new replies allowed.