0

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]);
LaRa
  • 3
  • 1
  • 3
  • Does this answer your question? [C++ error: "Array must be initialized with a brace enclosed initializer"](https://stackoverflow.com/questions/4329324/c-error-array-must-be-initialized-with-a-brace-enclosed-initializer) – Andrey Kartashov May 30 '20 at 02:15
  • `return dist[V][V]` accesses out of bounds – M.M May 30 '20 at 02:19
  • 2
    This stuff is 1000x easier if you use C++ arrays instead of C arrays – M.M May 30 '20 at 02:19
  • In C++ make an effort to avoid `#define` for constants and instead use things like `const int V = 4;` instead. This includes important type information. – tadman May 30 '20 at 02:19
  • Tip: Use `std::vector` as a container for your data and emulate the two dimensional structure. Don't mess around with C arrays unless you absolutely have to. – tadman May 30 '20 at 02:20

1 Answers1

0

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>.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62