首页 > 解决方案 > C 编程:将二维数组作为 const 函数参数传递时如何消除 QAC 警告?

问题描述

我想将一个二维数组传递给一个函数,并且该数组的值不会在该函数中被修改。所以我正在考虑这样做:

#include <Windows.h>

static INT8 TwoDimArrayConst(const INT8 ai_Array[2][2]);   

int main(void)
{
        INT8 ai_Array[2][2]       = { { { 1 }, { 2 } }, { { 3 }, { 4 } } };

  (void)TwoDimArrayConst(ai_Array);                           // Message 0432: [C] Function argument is not of compatible pointer type.

  return 1;
}

static INT8 TwoDimArrayConst(const INT8 ai_Array[2][2])
{
  INT8 test = 0;
  for (INT8 i = 0; i < 2; i++)
  {
    for (INT8 k = 0; k < 2; k++)
    {
      if (ai_Array[i][k] > 0)
      {
        test = 1;
      }
    }
  }
  if (test == 0)
  {
    test = 2;
  }

  return test;
}

但是,当我启用深度 5 QAC 设置时,它给了我 QAC 错误,因为我输入的是上面的代码注释:

// Message 0432: [C] Function argument is not of compatible pointer type.

如果我删除const函数声明和定义中的 ,那么函数就像:

static INT8 TwoDimArrayConst(INT8 ai_Array[2][2]);

这个错误会消失,但会有另一个错误说:

> The object addressed by the pointer parameter 'ai_Array' is not
> modified and so the pointer could be of type 'pointer to const'.

那么如何解决这个困境呢?我不能在 main 函数中将 ai_Array 定义为 const 数组,因为其他一些函数可能仍想修改该值。另外,我正在寻找在函数中仍然保持双括号(无需将行大小和列大小作为单独的参数传递)的解决方案,而不是将其视为一维数组。

标签: cmultidimensional-arrayqa-c

解决方案


以下建议的代码:

  1. 使用 C 库函数而不是 windows 函数,因为我在 linux 上运行,而不是 windows
  2. 执行所需的功能
  3. 干净地编译
  4. 利用 C 语言中的数组在内存中连续布局
  5. 利用“访问数组名称会降级为数组第一个字节的地址”
  6. 删除所有不需要的大括号(除了使代码混乱之外什么都不做)
  7. 记录为什么包含每个头文件
  8. 将数组的大小作为参数传递给被调用函数(应该始终这样做或在数组的内容中包含某种“标记”)
  9. 以上所有允许将数组视为一维数组
  10. 一旦遇到终止条件,就在被调用函数中跳出循环

顺便说一句:头文件:windows.h不可移植

现在,建议的代码:

//#include <Windows.h>
#include <stdio.h>    // printf()
#include <stdint.h>   // int8_t


static int8_t TwoDimArrayConst( const int8_t *ai_Array, size_t size );   

int main(void)
{
    const int8_t ai_Array[2][2]       = { { 1, 2 }, { 3, 4 }  };

    int8_t returnValue = TwoDimArrayConst(( int8_t* const )ai_Array, sizeof( ai_Array) / sizeof( int8_t ));                           

    printf( "%d\n", returnValue );
    return 1;
}


static int8_t TwoDimArrayConst( const int8_t *ai_Array, size_t size )
{
    int8_t test = 2;
    for ( size_t i = 0; i < size; i++)
    {
        if (ai_Array[i] > 0)
        {
            test = 1;
            break;
        }
    }

    return test;
}

运行建议的代码会导致:

1

推荐阅读