我有一个包含字节的固定大小的数组(它将始终具有相同的大小)。这是代码:
static void foo(uint8_t *arr_ptr);
void main()
{
uint8_t arr[4];
foo(&arr);
}
static void foo(uint8_t *arr_ptr)
{
for(uint8_t i=0; i<4; i++)
{
arr_ptr[i]=1; // Set to one just to make it simpler
}
}
想法是在 main 中有一个固定大小的数组作为缓冲区,并在每次调用 foo 时修改其内容。它可以正常工作,但它会给出一些警告和信息,让我觉得有些地方表述不正确。
At
static void foo(uint8_t *arr_ptr);
: INFO: expected 'uint8_t*{aka unsigned char }' but argument is of type 'uint8_t()[4]{aka unsigned char (*)[4]}'At
foo(&arr)
: WARNING: passing argument 1 of 'foo' from incompatible pointer type
在其他一些帖子中挖掘了一下,我发现也许一个解决方案是将其声明为 (*arr)[4]
,这可能有道理,但应用它们会使代码工作不同。我很确定我正在为这个指针声明和参数传递弄得一团糟,所以如果有人能帮助我澄清这些概念,我将不胜感激。
最佳答案
警告是因为传递的指针有另一种类型。
数组衰减为指针:
int arr[10];
foo(arr); /* <- array decals to the pointer to int. */
foo(&arr); /* <- array decals to the pointer to array of 10 ints. */
两个指针都引用内存中的同一个对象但具有不同的类型 - 因此出现警告。
关于c - 将固定大小的数组作为指针传递给函数时的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217455/