c - 定义不透明指针时防止不完整的类型声明?
问题描述
C 标准中有一个功能隐藏了我的代码中的错误,我想知道是否有某种方法可以防止它,或者至少发出警告。
在 C 中,此代码隐式声明struct foo
为不完整类型:
struct foo *ptr; /* I didn't even tell the compiler I wish to use struct foo */
但是,我宁愿被要求声明不完整的类型,如下所示:
struct foo; /* foo is incomplete, but I'm telling the compiler to allow references to foo */
struct foo *ptr; /* that's fine, pointer to an incomplete type which I said I wish to use */
我正在谈论的错误是我在指针定义中打错了字,因此它指向了一个不完整的类型,该类型是由编译器“动态”创建的,没有任何警告。如果编译器用“指向未声明结构的指针”之类的东西警告我,我会纠正错字。我可以以某种方式启用这样的警告吗?
解决方案
只要您不取消引用它或以需要完整类型的方式使用它,指针本身就可以。
如果你尝试你会得到一个错误。
例子:
struct foo; /* foo is incomplete, but I'm telling the compiler to allow references to foo */
void foo(void *vptr)
{
struct foo *ptr = ptr;
ptr -> x = 0; //error
}
#include <stdlib.h>
struct foo; /* foo is incomplete, but I'm telling the compiler to allow references to foo */
void foo(void)
{
struct foo *ptr = malloc(sizeof(*ptr)); // error - incomplete type
}
由于指向不完整类型的指针是有效的,因此不需要额外的警告消息。
推荐阅读
- keyboard-shortcuts - 用于在活动拆分视图之间切换的 Konsole 键盘快捷键?
- active-directory - 如何在客户端获取某个 GPO 的安全过滤属性?
- javascript - 如何监听输入中的段值(__/__/___)变化[type="date"]
- mysql - 如何使用 laravel 迁移交换两个索引字段?
- sql - 如何将架构及其所有表传输到新数据库?
- c# - C#/WPF 项目缺少 NuGet DLL 时出现神秘异常?
- amazon-web-services - 如何限制 IAM 用户的 S3 对象最大上传大小为 1 MB?
- r - 如何使用 R 中的循环绘制数据框中的每个变量
- c# - 我只需要显示我插入的多个图像
- java - Tic Tac Toe with swing - X 和 O 的不同颜色