c++ error: "array must be initialized with a brace-enclosed initializer"

LaRa

i need your help with this. my function is: (the way it works is true)

#include <iostream>              
using namespace std;

#define V 4  
#define INF 999 
int floydWarshall(int graph[][V]){  

        int dist[V][V], i, j, k;  


        for (i = 0; i < V; i++)  
            for (j = 0; j < V; j++)  
                dist[i][j] = graph[i][j];  

        for (k = 0; k < V; k++)  
        {  

            for (i = 0; i < V; i++)  
            {  

                for (j = 0; j < V; j++)  
                {  

                    if (dist[i][k] + dist[k][j] < dist[i][j])  
                        dist[i][j] = dist[i][k] + dist[k][j];  
                }  
            }  
        }  

        return dist[V][V];  
    }

and this line has the error array must be initialized with a brace-enclosed initializer:

int dist[V][V] = floydWarshall(graph[][V]);
Thomas Sablik

You can't use C arrays like other variables or objects in many cases. You can't pass a C array by value to a function or return a C array from a function. It will decay to a pointer to the first element. Therefore std::array was introduced in C++. It does exactly what you expected from C arrays in your code:

#include <array>

constexpr int V = 4;

auto floydWarshall(std::array<std::array<int, V>, V> graph){
    for (int k = 0; k < V; k++) {
        for (int i = 0; i < V; i++) {  
            for (int j = 0; j < V; j++) {  
                if (graph[i][k] + graph[k][j] < graph[i][j])  
                    graph[i][j] = graph[i][k] + graph[k][j];  
            }  
        }  
    }  
    return graph;  
}

With std::array you can pass a copy of the array to the function and don't need to copy it manually. You can return a copy of the array instead of using dynamic memory allocation and pointers.

You use the function with

auto dist = floydWarshall(graph);

where graph has type std::array<std::array<int, V>, V>.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related