2015-11-24 79 views
0

我試圖創建一個結構數組,其中每個框包含一個列表的頭。最初我使數組,然後我需要使用功能,以便使列表的節點。 我正在處理的問題與功能有關,因爲它不起作用。 我注意到知道我在做什麼錯... 代碼:通過函數在結構數組中創建一個列表

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

typedef struct 
{ 
    char user[50]; 
    char password[50]; 
    struct Photo *photohead; 
}User; 

typedef struct 
{ 
    int id; 
    char des[50]; 
    char name[50]; 
    char place[50]; 
    char date[50]; 
    struct photo *next; 
    struct Photo *prev; 
}Photo; 

User *CreateArray(); 
User *CreateArray(int size) 
{ 
    int i; 
    User *Userlist; 
    FILE *fp; 
    fp=fopen("clients.txt","r"); 
    if(fp==NULL){printf("failed to open file");} 
    Userlist=malloc(size*sizeof(User)); 
    for(i=0;i<size;i++) 
    { 
     fscanf(fp,"%s %s",Userlist[i].user,Userlist[i].password); 
     Userlist[i].photohead=(Photo*)malloc(sizeof(Photo)); 
     Userlist[i].photohead=NULL; 
    } 

    fclose(fp); 
    return Userlist; 
}; 

void option1(Photo **head,char name[50],char date[50], 
      char description[50],char location[50]) 
{ 

    Photo *temp; 
    temp=(Photo*)malloc(sizeof(Photo)); 
    temp=head; 
    while(temp->next!=NULL) 
    { 
     temp=temp->next; 
    } 

    temp->next=(Photo*)malloc(sizeof(Photo)); 
    strcpy(temp->next->name,name); 
    strcpy(temp->next->date,date); 
    strcpy(temp->next->des,description); 
    strcpy(temp->next->place,location); 

} 

int main() 
{ 
    char name[50],date[50],description[50],location[50]; 
    int option,user,sizze; 
    User *Users; 
    sizze=sizeofArray();//gets the size that the array needs to be from the file 
    Users=CreateArray(sizze) 
     PrintArray(Users,sizze); 

    printf("Enter the photos details\n"); 
    printf("Photos name:"); 
    scanf("%s",&name); 
    printf("\n"); 
    printf("Photos date:"); 
    scanf("%s",&date); 
    printf("\n"); 
    printf("Photos description:"); 
    scanf("%s",&description); 
    printf("\n"); 
    printf("Photos location:"); 
    scanf("%s",&location); 
    printf("\n"); 
    option1(&Users[user].photohead,name,date,description,location); 
} 
+1

...您將光頭設置了兩次... – nneonneo

+0

請使用4個空格縮進您的代碼以使其可讀。 – chqrlie

+1

代碼不能編譯。在'CreateArray(sizze)'之後缺少';'' – chqrlie

回答

2

struct Photostruct photo都是不確定的。

typedef struct { ... } Photo;應閱讀typedef struct Photo { ... } Photo;和修復的拼寫struct photo *next;

+0

好的答案,我正要說,關於錯字,但你有我,所以+1! – gsamaras

2

我認爲你的意思,而不是這樣的:

Userlist[i].photohead=(Photo*)malloc(sizeof(Photo)); 
Userlist[i].photohead=NULL; 

這樣的:

Userlist[i].photohead=(Photo*)malloc(sizeof(Photo)); 
Userlist[i].photohead.next=NULL; 

然而,這可能不完全解決你的問題。不管是什麼,拿一支鉛筆和一張紙,畫列表的行爲,通過執行手工代碼,考慮到三種情況:

  1. 第一個節點
  2. 中間節點
  3. 最後一個節點
相關問題