2016-09-20 114 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; 
} 

这就是你想达到的目的吗?