How to pass a 2-D array whose size is user-defined

Viewed 122

so this is my function it basically takes the 2 indexes and the 2D array and adds the weight to the intended place.

void AddEdge(int Vertex1Index, int Vertex2Index, int weight, int Edge)
{
    if (Vertex1Index==-1 || Vertex2Index==-1) // in case of invalid vertex
    {
        return ;
    }
    Edge [Vertex1Index][Vertex2Index] = weight; //using indexes to enter weight
}

the problem is that my size is defined by the user at the start of the program (its required to do so) other wise I would have made the size a global constant.

this is how you call the function

AddEdge(SearchVertex(Value, Size, Vertices),SearchVertex(Value1,Size, Vertices),weight, Graph);

Search vertex searches the input in the vertices array and returns the index. if the vertex does not exist it returns -1.

1 Answers

That would probably be better in a comment but I don't have the reputation for it..

Do you really need your array to be physically 2D?

What I mean is: you can define a matrix with fixed size (A[ROWS][COLS]) and access in the A[i][j] fashion or define a big array (single dimension) with size ROWS*COLS, even dynamically, and then access with A[i*COLS + j].

With this last approach you can pass the pointer in a much more flexible way to a function by giving also the matrix sizes.

If you allocate them dynamically, rows and cols can be user defined (not constant), it's just up to you how you access the memory inside the pointer, there's no strict positioning as it would happen with a "real" matrix, hence as long as your function knows the size, you are fine.

Your code would change as follows (you need cols in the function, mind that Edge is a pointer). You may also want to check for indexes out of bounds more carefully.

void AddEdge(int Vertex1Index, int Vertex2Index, int weight, int *Edge, int cols, int rows)
{
    if (Vertex1Index<=-1 || Vertex2Index<=-1 || Vertex1Index>=rows || Vertex2Index>=cols) // in case of invalid vertex
    {
        return ;
    }
    Edge [Vertex1Index * cols + Vertex2Index] = weight; //using indexes to enter weight
}

Where you'd allocate your array as follows.

int *Edge = new int(rows * columns); //both user defined
Related