0

I have written this code: Can someone tell me what the mistake am making? It's telling me that warning: taking sizeof array of runtime bound [-Wvla]

#include <bits/stdc++.h>
using namespace std;

bool bipartiteDfs(int node, vector<int> adj[], int color[]) {
    if(color[node]==-1)
        color[node]=1;
    
    for(auto it: adj[node]) {
        if(color[it]==-1) 
        {
            color[it] = 1-color[node];
            if(!bipartiteDfs(it, adj, color))
                return false;
        } 
        else if(color[node]==color[it])
            return false;
    }
    return true;
}
bool checkBipartite(vector<int> adj[], int n) {
    int color[n];
    memset(color, -1, sizeof color);
    
    for(int i=0; i<n; i++) {
        if(color[i] == -1) {
            if(!bipartiteDfs(i, adj, color))
                return false;
        }
    }
    return true;
}
int main() {
    int n, m;
    cin>>n>>m;
    vector<int> adj[n];
    for(int i=0; i<m; i++) {
        int u, v;
        cin>>u>>v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    if(checkBipartite(adj, n))
        cout<<"yes";
    else
        cout<<"no";
    return 0;
}

Error: warning: taking sizeof array of runtime bound [-Wvla]

  • `vector adj[n];` is not a valid C++ declaration. Same about `int color[n];`. There are no C-style variable length arrays in C++. You know how to use vectors. Use them. – n. m. could be an AI May 15 '22 at 06:27
  • There are all sorts of issues with VLAs which is why they aren't part of c++. sizeof not working with them is just one of them – Alan Birtles May 15 '22 at 06:30
  • Also note that your `memset` will set every byte of `color` to `-1` not set every `int` to `-1`. You should use `std::fill` instead (or just use a vector whose constructor can automatically initialise every element) – Alan Birtles May 15 '22 at 06:34
  • @AlanBirtles because of the way -1 is represented in two's complement, the end result is going to be the same. – Aykhan Hagverdili May 15 '22 at 06:48
  • @AyxanHaqverdili even if it happens to work in this instance it usually won't so is a bad habit to get into – Alan Birtles May 15 '22 at 07:36
  • @AlanBirtles I agree with you. I was commenting on the first sentence of your comment which claims it won't set elements to -1. – Aykhan Hagverdili May 15 '22 at 07:40

1 Answers1

0

VLA stands for "Variable Length Array". It is formally not a part of the C++ standard and you should not be using it. Use std::vector instead.

std::vector<int> color(n, -1);

Through this constructor, you don't even need a separate memset call.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93