S
S
shadrap2020-12-09 10:55:48
Arduino
shadrap, 2020-12-09 10:55:48

How to correctly pass a pointer to an array inside a structure to a C (Arduino) function?

Stuck on a seemingly simple moment. Sketch for the Arduino platform, compiling in Platformio. The sketch itself is very large, I will try to describe briefly.

There is a structure declared globally (stores data in the RTC memory of the chip):

#define ARRAY_SIZE 20
struct {
 .........
  uint32_t TimeStampData[ARRAY_SIZE];       // 80 byte
  uint16_t HumData[ARRAY_SIZE];             // 40 byte
  uint16_t TempData[ARRAY_SIZE];            // 40 byte
  uint16_t PresData[ARRAY_SIZE];            // 40 byte
  .................
   } MyRtcData;


there is a function CalculateTrend(?????????) // designed to perform the same calculations with the same arrays from the MyRtcData structure
{
int difference[11]={0,};
difference[0]=(MyRtcData.??????[0] - MyRtcData.&????[1])*1.5;
 difference[1]=(MyRtcData.?????[0] - MyRtcData.&????[2]);
................
}


there is a function unsigned int PrecipitationLikelihood(void) // from which I pass a pointer to an array from the structure to be processed to the above function.
{
....
int trend = CalculateTrend(MyRtcData.PresData);
}

Question - can I pass a pointer directly to a structure element (if it is described globally)? Or do I need to first pass the pointer to the structure, and then the pointer to the element of the structure? How can I access the elements of an array within a function?
Of course, here we can only consider passing through pointers, not entirely data, because small stack...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
U
User700, 2020-12-09
@shadrap

Yes, you can:
a) pass a pointer to uint16_t. In treyd, treat it as an array (of length known from define)
b) is it C or C++? In the latter, you can pass a reference to the uint16_t[number] type itself. Perhaps it will be possible to do this as a pointer to such a type
c) declare the type of the structure. There is such a thing as a pointer to a structure field. If it is global, then the pointer to it can not be passed to the function, but there it can be accessed directly. I can show you with an example.

A
Alexander Ananiev, 2020-12-09
@SaNNy32

Something like this

int CalculateTrend(MyRtcData* rcData)
{
   if(rcData != 0)
   {
        return rcData->PresData[0];
   }
  return -1;
}

S
shadrap, 2020-12-09
@shadrap

Yes, as I wrote at the beginning, the compiler says that it does not know MyRtcData ('MyRtcData' was not declared in this scope
) although I use this structure everywhere in the sketch.
the prologue of the function doesn't help either.... and that's not all you want!) I want something instead of
/cpp
return rcData->PresData[0]; // I want to have a variable pointer instead of PresData, i.e. and HumData ,TempData
/cpp

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question