1

I'm working on my I²C read function to pass an array pointer to a function and copy the data from the buffer.

Now I'm just testing the methodology of passing the array in code blocks to see the results.

My questions:

  1. Is the array passing to the function from main without correct?
  2. Also is my way of developing the function and passing the array as a pointer a good code strategy?

This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>

uint8_t reaArr (uint8_t len, uint8_t *data);

int main(void)
{
    uint8_t receive[9];
    uint8_t k;

    receive[9] = reaArr(9, receive);

    for (k=0; k<9; k++)
    {
        printf("%d\n", receive[k]);
    }

    return 0;
}

uint8_t reaArr (uint8_t len, uint8_t *data)
{

    uint8_t arr[9] = {20, 55, 66, 33, 5, 4, 45, 27, 59}, i, arrIndex = len;
    for (i=0; i<arrIndex; i++)
    {
        data[i] = arr[i];
    }

    return *data;
}
3
  • 1
    receive[9], here index out of bound, max index should be 8 Commented May 18, 2021 at 13:51
  • 1
    Also the last statement in reaArr, which is return *data is returning the first element of array data because name of an array is pointer to first element of the array so basically you dereferenced the pointer to first element of array data, and returned it. Commented May 18, 2021 at 14:01
  • 1
    Re "from main without correct": without what? Isn't a word missing? Please respond by editing your question, not here in comments (without "Edit:", "Update:", or similar - the question should appear as if it was written today). Commented May 27, 2021 at 20:33

1 Answer 1

1

Is the array passing to the function from main without correct?

Yes passing the array itself is correct, but you assign the result of the function to item number 10 here: receive[9] = .... Remember that arrays in C use 0-indexing, so this is out of bonds. You don't really need to return anything from the function in this case. Consider changing it to:

void reaArr (uint8_t len, uint8_t *data);

Also is my way of developing the function and passing the array as a pointer a good code strategy?

Generally, yes, caller allocation is preferred since that keeps allocation and algorithm separated. Had this example been a real I2C driver then you'd be reading from hardware buffers inside the function, instead of from a local array.

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.