如何解决使用数组作为全局变量 vs 局部变量
我一直在研究图形中的 DFS 算法,但一直在使用局部变量。 我有一个看起来像这样的代码:
#define MAX_VERTICES 50
typedef struck GraphType {
int n; // number of nodes
int adj_mat[MAX_VERTICES][MAX_VERTICES];
} GraphType;
int visited[MAX_VERTICES];
void insert_vertex(GraphType* g,int v) {
if (((g->n) + 1) > MAX_VERTICES) {
fprintf(stderr,"Graph: size of vertices ERROR");
return;
}
g->n++;
}
void insert_edge(GraphType* g,int start,int end) {
if (start >= g->n || end >= g->n) {
fprintf(stderr,"Graph: number of vertices ERROR");
return;
}
g->adj_mat[start][end] = 1;
g->adj_mat[end][start] = 1;
}
void dfs_mat(GraphType* g,int v) {
int w;
visited[v] = TRUE;
printf("vertex %d -> ",v);
for (w = 0; w < g->n; w++) {
if (g->adj_mat[v][w] && !visited[w])
dfs_mat(g,w);
}
int main(void) {
GraphType *g;
g = (GraphType*)malloc(sizeof(GraphType));
for (int i = 0; i < 4; i++)
insert_vertex(g,i);
insert_edge(g,1);
insert_edge(g,2);
insert_edge(g,3);
insert_edge(g,1,2);
dfs_mat(g,0);
free(g);
return 0;
}
我想要做的是将 visited[MAX_VERTICE] 数组变成一个局部变量(以便我可以将它作为参数提供给其他函数)。如何将其添加到主函数中并将其从全局使用中删除?也许通过使用指针?
解决方法
您只需在 main 函数中声明数组,并将其作为 int * 类型的参数传递给您需要的每个函数。
void dfs_mat(GraphType* g,int *visited,int v) {
int w;
visited[v] = TRUE;
printf("vertex %d -> ",v);
for (w = 0; w < g->n; w++) {
if (g->adj_mat[v][w] && !visited[w])
dfs_mat(g,w);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。