本周末学习 C ANSI 语言的特殊性,这是一个相当大的挑战。
在一个练习中,我得到了一个头文件,其中包含一些函数签名声明。
这个引起了我的注意:
typedef struct image * Image;
我在我的 .c 文件上试过这个:
typedef struct {
char nbrMagique[10];
unsigned long imgLarg;
unsigned long imgHaut;
unsigned long imgSeuilMax;
unsigned long **imageMatrice;
} Image;
但是编译的时候一直报错:
imagePGM.c:22:3: erreur: conflicting types for ‘Image’
} Image;
所以我想因为我无法在 .c 文件中重新定义结构,而且我也无法触及 header 。
并尊重“typedef struct image * Image;”在 .h 头文件中,我必须创建一个动态二维表并将指针 *image 指向它?
我是不是漏掉了什么?
但是 typdef 签名中的指针 * 在 .h 文件之一中意味着什么?
最佳答案
来自 typedef
的语义,章节 §6.7.8,C11
文档,
In a declaration whose storage-class specifier is
typedef
, each declarator defines an identifier to be a typedef name that denotes the type specified for the identifier [...]
所以,基本上,typedef
用于为给定类型创建别名。
此外,为了扩展这一点,
A
typedef
declaration does not introduce a new type, only a synonym for the type so specified. That is, in the following declarations:
typedef T type_ident;
type_ident D;
type_ident
is defined as atypedef
name with the type specified by the declaration specifiers inT
(known asT
), and the identifier inD
has the type ‘‘derived-declaratortype- list T ’’.
在您的代码中,您试图将两种不同的类型typedef
(即struct image *
和未命名的struct
)转换为相同的类型别名,这是问题的原因。
解决方案:您不需要在.c
文件中typedef
结构声明,使用简单的声明,例如
struct image {
char nbrMagique[10];
unsigned long imgLarg;
unsigned long imgHaut;
unsigned long imgSeuilMax;
unsigned long **imageMatrice;
} ;
也就是说,一般来说,typedef
指针被认为是一种令人困惑的编码风格,这会降低可读性,恕我直言,请避免使用 typedef 指针。
关于部分
But what does the pointer
*
in the signature of thetypedef
mean?
意思是,新的别名是指针类型。对于这种情况,
typedef struct image * Image;
两者
Image iPointer = NULL;
和
struct image * againIPointer = NULL;
相同。
关于c - 带指针的 typedef 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40713899/