c - 带指针的 typedef 声明

标签 c pointers syntax typedef

本周末学习 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 a typedef name with the type specified by the declaration specifiers in T (known as T), and the identifier in D 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 the typedef mean?

意思是,新的别名是指针类型。对于这种情况,

 typedef struct image * Image;

两者

 Image iPointer = NULL;

 struct image * againIPointer = NULL;

相同。

关于c - 带指针的 typedef 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40713899/

相关文章:

c - 同时标记匹配和转义匹配外的特殊字符

c - 段错误 : Quadratic Equation Solver from text file in C

c - 将初始值设置为 c 中结构的字段?

c++ - 如何处理复制指针的释放

c - 为指向 C 中记录的指针中的键赋值

c - 如何修复代码以打开代码块中命令提示符中传递的文件

C 指针到指针。为什么需要有两个星号?

syntax - 在 OCaml 中,你如何区分 * 和 ,?

python - def main() 无效语法、开发服务器和终端

sql-server - SQL# 符号是什么意思以及如何使用它?