c - 将 'typedef struct' 数组传递给函数

标签 c arrays typedef

我有以下情况:

文件 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

  1. 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 keyword static 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/

相关文章:

c++ - Ubuntu 16.04 下的 Android linphone 构建给出 CC 和 CXX 的 cmake 路径变量错误?

c - Linux C读取文件UNICODE格式文本(记事本Windows)

c - malloc.c 3096 有什么问题

c - 这个for循环是如何工作的?

c# - 数组乘对

android - JSON异常 : Value -- array hasn't got a label

c - 二维数组和指针有什么关系?

c++ - typedef 函数指针?

c - typedef 结构体用法

C函数指针和typedef