是否可以只在开始时声明一个类型,而后在C中定义它呢?

时间:2019-03-01 17:46:47

标签: c typedef

在此示例中,Book的完整定义在main()中使用之前。有没有一种方法可以将Book声明为类型而不指定详细信息,但是可以在main()之后定义详细信息。谢谢。

https://www.tutorialspoint.com/cprogramming/c_typedef.htm

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

typedef struct Books {
   char title[50];
   char author[50];
   char subject[100];
   int book_id;
} Book;

int main( ) {

   Book book;

   strcpy( book.title, "C Programming");
   strcpy( book.author, "Nuha Ali"); 
   strcpy( book.subject, "C Programming Tutorial");
   book.book_id = 6495407;

   printf( "Book title : %s\n", book.title);
   printf( "Book author : %s\n", book.author);
   printf( "Book subject : %s\n", book.subject);
   printf( "Book book_id : %d\n", book.book_id);

   return 0;
}

2 个答案:

答案 0 :(得分:3)

您可以预先声明并输入typedef:

typedef struct Books Book;

这将允许您使用类型Book*的指针,但不允许您取消引用它们(无论是*还是->)或声明此类型的对象(与Book book;一样)。

与实现您所陈述的目标最接近的事情可能是 返回指向已分配的Book并随后带有访问器函数的指针的函数。

它将编译:

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

typedef struct Books Book; //forward declare + typedef
Book *Book__alloc(void);
//accessor functions:
char*Book__title(Book*);
char*Book__author(Book*);
char*Book__subject(Book*);
int *Book__id(Book*);


int main( ) {

   Book *book = Book__alloc();
   if(!book) return EXIT_FAILURE;

   strcpy( Book__title(book), "C Programming");
   strcpy( Book__author(book), "Nuha Ali"); 
   strcpy( Book__subject(book), "C Programming Tutorial");
   *Book__id(book) = 6495407;

   printf( "Book title : %s\n", Book__title(book));
   printf( "Book author : %s\n", Book__author(book));
   printf( "Book subject : %s\n", Book__subject(book));
   printf( "Book book_id : %d\n", *Book__id(book));

   free(book);

   return 0;
}

//provide definitions after the fact
struct Books {
   char title[50];
   char author[50];
   char subject[100];
   int book_id;
};
Book *Book__alloc(void){ return malloc(sizeof(Book)); }
char*Book__title(Book*X){ return X->title; }
char*Book__author(Book*X){ return X->author; }
char*Book__subject(Book*X){ return X->subject; }
int *Book__id(Book*X) { return &X->book_id; }

答案 1 :(得分:2)

尽管有人评论说这是可能的,但我不这样认为,所以我的回答是“否”。仅仅是因为在main()中已经使用了Book类型,例如

strcpy( book.author, "Nuha Ali");

如果不了解Books结构,实际上可以由编译器处理吗?
在函数声明中可能是这样的,

typedef struct Books Book;
void foo(struct Books *aBookPtr); 

这是因为编译器可以愉快地使用其指针的知识 并且仅需在实施中提供详细信息。希望这会有所帮助。