简体   繁体   中英

How to pass multi-dimensional array to header file in C++

I am trying to work with multi-dimensional arrays. My goal is to have a separate file for my matrix functions, however I am having trouble with setting the value of V .

Error : 'V' was not declared in this scope Since this error statement is very broad, I could not find a satisfactory answer on my searches.

This is what I want to implement.

main.cpp

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

int main()  
{   int V = 5;
    int graph[V][V] = { {... },  
                        {... },  
                        {... },   
                        {... },   
                        {... } };    
    func1(graph);
    func2(graph); 
    return 0;  
}

prims.h

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

int func1(int graph[V][V]);
int func2(int graph[V][V]);

#endif

prims.cpp

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

int func1(int graph[V][V])  
{  
  // function
} 

int func2(int graph[V][V])  
{  
  // function
}

Please comment below if more clarification is required. Thank you.

Since you want to set the value from main, one alternative is to declare V as global variable in main and as extern const int in prims.h, so that it is visible in prmis.cpp as well.

prims.h

extern const int V;

main.cpp

const int V = 5; //declared as global in main
int main()  
{  
   /* */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM