AnsweredAssumed Answered

handling variable length arrays?

Question asked by ROB LUND on Aug 31, 2010
Latest reply on Sep 2, 2010 by bigmac

Is there a good way of handling variable length arrays that I'm just not seeing?  Here's what I have.

 

I'm writing a general purpose I2C library with all the usual suspects, like Start, Stop, Ack, Nack, Write, and Read functions, etc.  For the Read function, I'd like to accommodate a range of I2C slave peripherals.  For instance, I've used devices that have no registers, some that do have registers, the majority of which only return single octets of data at a time when read, but some that return multiple octets.  So I figured it would be cool to make the Read function such that I could send it how many bytes to read back.  Well, this requires some allocated memory block, say an array, to dump into.

 

But if this Read function is general purpose, then the array depth is not known at compile time.  I tried writing my function to return a pointer to a static memory location.  Trouble is, the compiler only allocates the first data byte pointed to by this pointer.  The rest of the data is in unallocated space and might get trampled on.

 

I finally gave up and just created a global array that I knew would be big enough for most devices.  Then I call my Read function and pass it a pointer to this array.

 

Not elegant!  Any suggestions?

Outcomes