Hi all
I'm trying to write some basic code where a function returns an array - or rather returns a pointer to the array.
I'd prefer to do it this way, as it's going to get moved into a library, and I think it'd be "cleaned" to do it like this, as opposed to have the function modify a global array.
However, I'm having trouble with some code I wrote for myself as a proof of concept. Very simply, I'm using a function to create an array, and return the pointer to it. The main code then looks at the pointer and retreives the relevent number of bytes.
I'd be very glad of any suggestions!
int arraySize = 7;
void setup()
{
Serial.begin(9600);
randomSeed(analogRead(0) * analogRead(1));
byte * bytePointer = randomByteArrayPointer(); //bytePointer is a pointer to the first byte in the array (??)
Serial.print("Output as main code trys to read pointer - ");
for(int i = 0; i < arraySize; i++)
{
Serial.print((int)bytePointer[i], HEX); // <-- this line not working!
Serial.print(",");
}
Serial.println("");
}
void loop()
{
}
byte randomByte()
{
return (byte)random(255);
}
byte * randomByteArrayPointer() //pointer to he array
{
byte myArray[arraySize];
Serial.print("Output as bytes are created - ");
for(int i = 0; i < arraySize; i++)
{
myArray[i] = randomByte();
Serial.print((int)myArray[i], HEX);
Serial.print(",");
}
Serial.println("");
return myArray; //returns pointer to first byte of array
}
It produces the following output (with resets in between):
Output as bytes are created - 8,3B,47,6D,56,61,E,
Output as main code trys to read pointer - 0,5,14,4,0,2,85,Output as bytes are created - DE,79,26,AD,82,C6,E4,
Output as main code trys to read pointer - 0,5,1,FF,0,2,84,Output as bytes are created - 6A,42,8F,F7,FE,42,F6,
Output as main code trys to read pointer - 0,5,1B,4,0,2,83,Output as bytes are created - 8,AE,73,AF,76,D3,35,
Output as main code trys to read pointer - 0,5,0,0,0,2,83,
I thought I'd got my head around pointers and arrays, but clearly not!
Thanks
Olly