使用数组作为全局变量 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);
}