主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C:2012 Rule 12.5

The sizeof operator shall not have an operand which is a function parameter declared as “array of type”

描述

规则定义

The sizeof operator shall not have an operand which is a function parameter declared as “array of type”. 1

此规则来自 MISRA C™:2012 Amendment 1。

理由

作用于数组的 sizeof 操作符通常返回数组的大小(以字节为单位)。例如,在以下代码中,sizeof(arr) 返回 arr 的字节大小。

int32_t arr[4];
size_t numberOfElements = sizeof (arr) / sizeof(arr[0]);

但是,当数组是函数参数时,它会退化为指针。作用于数组的 sizeof 操作符返回相应的指针大小,而不是数组大小。

在函数参数数组上使用 sizeof 操作符通常表示编程错误。

报告中的补充消息

The sizeof operator shall not have an operand which is a function parameter declared as “array of type”.

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

#include <stdint.h> 
int32_t glbA[] = { 1, 2, 3, 4, 5 };
void f (int32_t A[4])
{
 	uint32_t numElements = sizeof(A) / sizeof(int32_t);  /* Non-compliant */
	uint32_t numElements_glbA = sizeof(glbA) / sizeof(glbA[0]);  /* Compliant */
}

在此示例中,无论数组中出现多少个成员(此例中为 4 个),变量 numElements 的值始终为 1,因为 A 的类型为 int32_t *,而不是 int32_t[4]

变量 numElements_glbA 的值为 5,因为运算符 sizeof 作用于全局数组 glbA

检查信息

组:表达式
类别:强制
AGC 类别:强制

版本历史记录

在 R2017a 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace® Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.