我希望将一个2D数组传递给一个函数,并且数组的值将不会在该函数中被修改。所以我正在考虑这样做:
#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;
}但是,当我启用depth 5 QAC设置时,它给了我QAC错误,因为我把它放在上面的代码注释中:
// Message 0432: C函数参数不具有兼容的指针类型。
如果删除函数声明和定义中的const,则函数如下:
static INT8 TwoDimArrayConst(INT8 ai_Array[2][2]);此错误将消失,但还会出现另一个错误,即:
指针参数'ai_Array‘所寻址的对象没有>修改,因此指针可以是’指向const的指针‘类型。
那么,如何解决这一困境呢?我不能将ai_Array定义为主函数中的const数组,因为其他一些函数可能仍然希望修改该值。另外,我正在寻找的解决方案仍然是在函数中保持双括号(不需要将行大小和列大小作为单独的参数传递),而不是将其视为一维数组。
发布于 2019-02-19 01:51:48
下列拟议守则:
BTW:头文件: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;
}运行拟议的代码将导致:
1https://stackoverflow.com/questions/54750704
复制相似问题