2016-09-20 59 views
-2

我有一個結構與其內的另一個結構數組,我無法初始化結構。如何在結構中初始化一個struct數組?

typedef struct stack * Stack; 
typedef struct book * Book; 

struct book { 
    char *title; 
    int pages; 
}; 

struct stack { 
    int num_books; 
    Book array[50] 
}; 

我所試圖做的是零本書籍創建一個空的堆棧,但我一直在我什麼都試過讓段故障。

這裏是我的初始化函數:

Stack create_stack(void) { 
    Stack s = malloc(sizeof(struct stack) * 50); 
    s->num_books = 0; 
    // s->array[0]->title = Null; 
    // s->array[0]->pages = 0; 
    // the above 2 lines give a seg fault: 11 
    // I also tried: 
    // s->array = s->array = malloc(sizeof(struct book) * 50); 
    // Which gives the error that array type 'Book [50]' is not assignable 
    return s; 
} 

如何創建零本書籍空棧?

+2

你需要將malloc作爲'sizeof(struct stack)'的malloc。 50本書的「數組」(它們是typedef的指針)作爲'stack'結構的一部分。 – Hypino

+4

永遠不要使用typedef指針。它只會造成混亂。特別是,看起來像50本書的數組實際上只是50個指針的數組。所以你需要爲這些指針分配內存,然後才能使用它們。 – user3386109

+0

您今天已經問過類似的問題了!你應該遵循你在第一個問題中得到的建議,並在繼續之前先修復缺陷/錯誤!並且在你的代碼中''struct''中沒有'struct'數組! – Olaf

回答

2

您還沒有爲struct book對象分配內存。結構體:

struct stack { 
    int num_books; 
    Book array[50]; 
}; 

定義array構件50元件的指針book結構陣列(即,Book是同義詞struct book *)。這些仍然是「狂野」指針,並且您需要爲它們分配分配的結構對象。換句話說,通過調用:

Stack s = malloc(sizeof(struct stack) * 50); 

你已經爲struct stack類型五十對象的房間,但裏面的每一個結構的,有餘地struct book指針,而不是對象本身。

像在評論中提到的一樣,typedefing指針類型是混淆代碼的簡單方法。

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

#define SIZE 2 

typedef struct book { 
char * title ; 
int pages; 
} Book; 

typedef struct stack { 
int num_book; 
Book book_arr[SIZE]; 
} Stack; 

//------------------------------------------------ 

int main (void){ 

Stack s1; 
    printf("Enter Number of Books : "); 
    scanf("%d",&s1.num_book); 
    getchar(); 

    //BOOK 
     for(size_t j = 0 ; j < s1.num_book ; j++){ 
     char temp[100]; 
     printf("Enter the Book Title for %zd Book : ", (j+1)); 
     fgets(temp,100,stdin); 
     strtok(temp,"\n");  // for removing new line character 
    s1.book_arr[j].title = malloc (sizeof(temp) +1); 
    strcpy(s1.book_arr[j].title,temp); 
        // puts(s1.book_arr[j].title); 
     printf("Enter Pages for %zd Book : ",(j+1)); 
    scanf("%d",&s1.book_arr[j].pages); getchar(); 
     } 
      //PRINT 
size_t count = 0 ; 
     for(size_t i = 0 ; i < s1.num_book ; i++){ 
    while(count < SIZE) { 
     printf("Book Title : %s\nBook pages : %d\n",s1.book_arr[count].title, s1.book_arr[count].pages); 
     free(s1.book_arr[count].title); 
     count++; 
     } 
}  
return 0; 
} 

這就是你想達到的目的嗎?