繁体   English   中英

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

[英]How to initialize an array of struct in a 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;
}

如何创建零书的空堆栈?

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

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

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

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

您为struct stack类型的 50 个对象腾出了空间,但是在这些结构中的每一个内部,都有空间用于struct book指针,而不是对象本身。

就像注释中提到的那样,对指针类型进行 typedefing 是一种混淆代码的简单方法。

#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;
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM