我有以下情况:
文件 A.c:
typedef struct element
{
uint16_t value_raw;
float value_scaled;
char *desc;
} element;
element sv[REG_READ_COUNT];
文件 A.h:
typedef struct element element;
文件 B.c:
#include "A.h"
void dostuff (element sv[]) { }
在编译时我得到 “错误:数组类型的元素类型不完整” 对于 B.c 中的函数参数定义。
执行此操作的正确方法是什么? 如何将“元素”类型的数组传递给函数?
最佳答案
在B.c
中,element
是一个不完整的类型(在A.h
中没有定义,只在A.c
中定义) ). C 不允许数组声明符具有不完整的元素类型(如您所见)。以下是 C99 草案中的相关文本:
6.7.5.2 Array declarators
Constraints
- In addition to optional type qualifiers and the keyword
static
, the[
and]
may delimit an expression or*
. If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. If the expression is a constant expression, it shall have a value greater than zero. The element type shall not be an incomplete or function type. The optional type qualifiers and the keywordstatic
shall appear only in a declaration of a function parameter with an array type, and then only in the outermost array type derivation.
强调我的。这适用于所有数组声明符,无论它们出现在哪里:在变量声明、typedef、函数参数列表等中。
要修复您的代码,请将完整的结构定义放在 A.h
中。或者,如果 dostuff
实际上不需要处理元素(例如,只是将“数组”传递给其他函数),您可以使用 void dostuff(element *sv)
.
关于c - 将 'typedef struct' 数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838498/