如何使用位图2D数组存储图形的邻接矩阵

时间:2014-10-03 08:37:53

标签: c arrays bitmap

我想存储一个非常大的图形(大约40k个节点)的邻接矩阵。但是使用int和char数组因为内存限制而导致分段错误。使用malloc的动态分配也失败了。任何人都可以建议使用位图2D阵列实现此方法吗? 这是我到目前为止在C中的实现:

#include <stdio.h>
#include <stdlib.h>

int MAX = 50000;

void clustering(char adj[][MAX]);

int count_neighbour_edges(int temp[], int len, char adj[][MAX]);

int main()
{
   int nol = 0, i, j, k;    
   FILE *ptr_file1,*ptr_file2;

   struct community
   {
      int node;
      int clust;
   };
   struct community d;

   ptr_file1 = fopen("community.txt","r");

   if (!ptr_file1)
    return 1;

   while(fscanf(ptr_file1,"%d %d",&d.node, &d.clust)!=EOF)  //Getting total no. of nodes from here
   {
     nol++;
   }

   char adj[nol+1][nol+1];     //Getting segmentation fault here    

   struct adjacency
   {
       int node1;
       int node2;
   };
   struct adjacency a;

   ptr_file2 = fopen("Email-Enron.txt","r");

   if (!ptr_file2)
    return 1;




    while(fscanf(ptr_file2,"%d %d",&a.node1, &a.node2)!=EOF)
    {
       adj[a.node1][a.node2] = '1'; 
       adj[a.node2][a.node1] = '1'; 
    } 

    clustering(adj);
    return (0);
}

1 个答案:

答案 0 :(得分:0)

您可以尝试将数组放入DATA段。你可以在任何函数之外声明它,然后将该内存区域用作动态大小的二维数组:

char buffer[MY_MAX_SIZE];

int main()
{

...

    if ((nol+1)*(nol+1) > MY_MAX_SIZE) {
        exit(1);   // Too large to fit in buffer!
    }
    char (*adj)[nol+1] = buffer;     // Use the space in buffer as a dynamic 2-dimensional array. 

稍微不直观的声明是因为nol的大小在编译时是未知的,所以我不能将缓冲区声明为你想要的大小的二维数组。

您需要确定适合问题大小且您的平台可以处理的MY_MAX_SIZE值,例如

#define MY_MAX_SIZE (40000L * 40000L)