簡體   English   中英

結構聲明中需要typedef

[英]typedef required in struct declaration

我正在嘗試創建一個struct元素數組,如下所示:

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

struct termstr{
double coeff;
double exp;
};

int main(){

termstr* lptr = malloc(sizeof(termstr)*5);

return 0;
}

當我編譯它時,出現如下錯誤:

term.c: In function ‘main’:
term.c:11:1: error: unknown type name ‘termstr’
term.c:11:31: error: ‘termstr’ undeclared (first use in this function)

但是,當我將代碼更改為以下代碼時,它會照常編譯:

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

typedef struct termstr{
double coeff;
double exp;
}term;

int main(){

term* lptr = malloc(sizeof(term)*5);

return 0;
}

我添加了typedef(類型名稱為term),將struct的名稱更改為termstr,並以term *作為指針的類型分配內存。

在這種情況下(即創建結構數組)是否總是需要typedef? 如果不是,為什么第一個代碼給出錯誤? 是否還需要typedef創建和使用結構的單個實例?

第一種類型不起作用,因為您在termstr之前忘記了struct關鍵字。 您的數據類型是struct termstr ,而不僅僅是termstr 當您輸入typedef ,結果名稱將用作struct termstr的別名。

甚至您也不需要這樣做。 使用typedef更好:

順便說一句,不要忘記釋放內存:

閱讀為什么要使用typedef?

您的工作代碼應為:

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

struct termstr{
  double coeff;
  double exp;
};

int main(){

struct termstr* lptr = malloc(sizeof(struct termstr)*5);
free(lptr);
return 0;
}

它應該是:

struct termstr * lptr = malloc(sizeof(struct termstr)*5);

甚至更好:

struct termstr * lptr = malloc(sizeof(*lptr)*5);

在C語言中,數據類型的名稱是“ struct termstr”,而不僅僅是“ termstr”。

您可以執行以下操作:

typedef struct termstr{
   double coeff;
   double exp;
} termstrStruct;

然后,您只能使用termstrStruct作為結構的名稱:

termstrStruct* lptr = malloc(sizeof(termstrStruct)*5);

它並不總是必需的,您只需編寫struct termstr

不要忘記free分配的內存!

Typedef是簡化此操作的便捷方法:

struct termstr* lptr = (struct termstr*)malloc(sizeof(struct termstr)*5);

對此:

typedef struct termstr* term;
term* lptr = (term*)malloc(sizeof(term)*5);

強制轉換malloc也是一個好主意!

如果您想單獨使用typename termstr,則可以使用typedef:typedef struct {double a; 雙b; } termstr;

在C語言中,您還需要添加struct關鍵字,因此您可以使用typedef將別名與“ struct termstr”鏈接起來,或者需要編寫類似

struct termstr* lptr = malloc(sizeof(struct termstr)*5);

但是,在C ++中,您可以直接將其引用為'termstr'(請閱讀:在那里不再需要struct關鍵字)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM