2013-03-10 45 views
-2

我得到的是什么使本作的问题,我只看到了作为解释这在C

for(i=0;nlist[i].nid!=0;i++) 
     {} 
     nlist[i].nid=n_id; 
     nlist[i].add=temp; 

NLIST是结构类型的数组

结构

struct node 
{ 
    int id; 
    struct node *l[MAX_CONN+1]; 
    int cost[MAX_CONN+1]; 
    struct node **next; 
    int *mincost; 

}; 
typedef struct node nodes; 
struct record 

{ 
    int nid; 
    struct node *add; 
}; 
typedef struct record records; 
records nlist[MAX_NODES+1]={0}; 
实施

全功能

FILE *f; 
    int d; 
    int i=0,j=0,n_id,n_cost; 
    nodes *temp=0,*temp1=0; 

    if((f=fopen("graph.txt","r"))== NULL) 
    { 
     printf("Error opening file.\n"); 
     exit(1); 
    } 
    memset(nlist, 0, sizeof(struct record) * MAX_NODES); 
    count=0; 
    do /*first get the id and address of all nodes*/ 
    { 
     fscanf(f,"%d",&n_id); 
     for(i=0;nlist[i].nid!=0;i++) 
     { 
      if(n_id==nlist[i].nid) 
      { 
       printf("Id already exists."); 
       return; 
      } 
     } 
     temp=(nodes *)malloc(sizeof(nodes)); 
     if (temp == 0) 
     { 
      printf("ERROR: Out of memory\n"); 
      return; 
     } 
     memset(temp, 0, sizeof(struct node)); 
     temp->id=n_id; 
     temp->l[MAX_CONN+1]=0; 
     temp->cost[MAX_CONN+1]=0; 
     for(i=0;nlist[i].nid!=0;i++) 
     {} 
     nlist[i].nid=n_id; 
     nlist[i].add=temp; 
     count++; 
     while((d=fgetc(f)!=';')) 
     {} 
    }while((d=fgetc(f))!=EOF); 

    rewind(f); 

    for(i=0;i<count;i++) /*now get the information of all nodes connections.*/ 
    { 
     fscanf(f,"%*d"); 

     temp=nlist[i].add; 
     while((d=fgetc(f)!=';')) 
     { 
      fscanf(f,"%d-%d",&n_id,&n_cost); 
      for(j=0;nlist[j].nid!=0;j++) 
      { 
       if(nlist[j].nid==n_id) 
       { 
        temp1=nlist[j].add; 
        break; 
       } 
      } 
      for(j=0;temp->cost[j]!=0;j++) 
      {} 
      temp->cost[j]=n_cost; 
      temp->l[j]=temp1; 
     } 
    } 
    fclose(f); 
+5

呃,什么?........... – 2013-03-10 04:26:01

+0

什么是nlist?结构体?联盟? – Deepu 2013-03-10 04:30:18

回答

2

缩进是误导。应缩进更多这样的:

for(i=0;nlist[i].nid!=0;i++) { 
    /* empty loop */ 
} 
nlist[i].nid=n_id; 
nlist[i].add=temp; 

我认为,它应该做的是如下:for循环推进从0 i,直到找到具有空值,其nid领域nlist元素。然后它将该索引处的nidadd字段分别设置为n_idtemp

我应该补充说这是非常危险的代码。如果inlist的末尾前进,但未找到合适的位置,则该程序很可能会崩溃或以其他方式行事不当。它当然不会表现正确。

+0

更有可能这些语句应该在循环中!但是考虑到使用i的循环终止条件,无论如何它都没有多大意义。 – 2013-03-10 04:28:55

+0

@MitchWheat - 这个或者一些评论会大大提高可读性。我的首选是将'for'移动到一个有意义名称的函数中(例如,'findFirstAvailableSlot()'返回一个索引(如果没有可用的话,则返回-1) – 2013-03-10 04:31:22

+1

我的偏好是挖一个大洞,把代码放入它!:) – 2013-03-10 04:32:17