2014-11-23 219 views
-1

我想了解一段代码中的struct用法。这让我非常困惑。看起来像typedef在同一个结构体上使用两次。请任何人都可以帮我理解为什么这段代码有两次typedef。有什么办法可以简化这段代码。 非常感谢您的时间。typedef在相同的结构上使用两次

typedef struct { 
city_t* cities; 
int count;  
cost_t cost;  
} tour_struct; 
typedef tour_struct* tour_t; 


typedef struct { 
tour_t* list; 
int list_sz; 
int list_alloc; 
} stack_struct; 
typedef stack_struct* my_stack_t; 
+0

'tour_struct'是一个结构。 'tour_t'是一个'tour_struct *',也就是'tour_t'是一个指向结构类型的指针,定义为tour_struct – nhgrif 2014-11-23 16:19:34

回答

2

第一个typedef给出了(匿名)结构的一个类型名。第二个typedef定义了另一个指针的类型。

tour_struct tour; // declares a struct. 
tour_t ptr; // declares a pointer to a struct. 
0

第一类型定义是在一个典型的方式使用在C 申报结构我想你指的是第二类型定义: 的typedef tour_struct * tour_t; 它被使用,因为这里被声明为另一个名称(别名)指针上面声明的结构。这就是为什么使用第二个typedef的原因。

+0

我可以改变我的代码并且仍然有相同的含义。 struct tour_struct { city_t * cities; int count; cost_t cost; }; struct stack_struct {0} struct tour_struct * list; int list_sz; int list_alloc; }; struct stack_struct * my_stack_t; – user3551094 2014-11-23 16:27:40

0

在typedef中的已知类型之后使用'*'只是定义了一个指向该类型的指针。

typedef stack_struct* my_stack_t; 

将定义一个指针stack_struct和将它称为my_stack_t