3

I have a fixed size array (which will be always of the same size) containing bytes. Here is the code:

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
    }
}

The idea is to have a fixed size array at main as a buffer, and modify its content every time foo is called. It works as it should, but it gives some warnings and info's that makes me think something is not correctly stated.

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

Digging a bit at some other posts, I've seen that maybe a solution could be to declare it as (*arr)[4], which may have sense, but applying them makes the code work different. I'm pretty sure I'm making my mind a mess with this pointer declaration and argument passing, so I'd appreciate if someone can help me clarify these concepts.

5
  • 10
    Don't pass the address of the array, an array is already (decays into) a pointer when passed to a function: foo(&arr); --> foo(arr); Commented May 20, 2019 at 8:58
  • 3
    &arr is a pointer to the array itself, it has the type uint8_t (*)[4]. You want to pass a pointer to the first element, which is &arr[0], or plain arr as that will decay to a pointer to the first element. That pointer will have the expected type of uint8_t *. Commented May 20, 2019 at 9:00
  • Thank you @KeineLust and@some-programmer-dude, that fixed the warnings. Anyway, that means that passing an array as it is to a function will always pass it as a pointer? So modifying it will modify it in main too... Commented May 20, 2019 at 9:10
  • @user11527039 yep! Commented May 20, 2019 at 9:18
  • Your current function already is modifying the contents of the array. Or did you mean something else? Commented May 20, 2019 at 9:26

1 Answer 1

2

The warning is because the passed pointer has another type.

Arrays decay to pointers:

int arr[10];

foo(arr); /* <- array decals to the pointer to int. */
foo(&arr); /* <- array decals to the pointer to array of 10 ints. */

Both pointers reference the same object in the memory but have different types - hence the warning.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.