如何在结构中初始化struct数组?

时间:2016-09-20 20:47:55

标签: c arrays 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 个答案:

答案 0 :(得分:2)

您尚未为struct book个对象分配内存。结构:

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

array成员定义为指针book struct的50个元素数组(即Bookstruct book *的同义词)。这些仍然是“狂野”指针,您需要为它们分配已分配的结构对象。换句话说,通过调用:

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

你已为50个struct stack类型的对象留出了空间,但在每个结构中,有struct book个指针的空间,而不是对象本身。

就像在评论中提到的那样,键入定义指针类型是一种模糊代码的简单方法。

答案 1 :(得分: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;
}

这是你想要实现的目标吗?