How to use pointers ?

I am new to programming in arduino & C, and don't really understand how to return an array from a function.
I want to get an array of integers from a function back into the main loop (rather than putting the lengthy function in the main loop. I'm guessing I have to use pointers ?
Here is simple/cut down code to show what I've done.

void loop() {
int code = readCode();
for(int i = 0; i < 10; i++){
Serial.print(code
);*

  • }*
    }
    int *readCode() {
  • int rcode[10];*
  • //Place some values into rcode array*
  • return rcode;*
    }
    This is just returning wierd random values.
    "rcode" within the function is definately being populated correctly.

"rcode" in "readCode" is what is known as an "automatic variable". Space for it is allocated on the stack when you start to execute "readCode" and this storage is released when you exit "readCode", so you cannot return a pointer to it and expect it to contain sensible values, because calling another function could reassign the storage that was used.
The pointer will point to a valid address, but the data at that address may have been over-written by another function.

If you called another function from within "readCode", then you could pass that function a pointer to "rcode" (because it is pointer to storage that is still valid), but unless you declare it "static", you can't pass a pointer to it out of the function it is declared in.

int *readCode() {
static int rcode[10];
....

If you are new to C you may be better of avoiding pointers if you can.

If rcode is a global array (i.e. it is declared at the top of your sketch outside of any sketch functions, then your readCode function can read and write the elements of rcode using an index.

here is an example fragment:

int rcode[10]; // global array 

void loop() { 
     for(int i = 0; i < 10; i++){
       int code = readCode(i);
       Serial.print(code);
     }
} 

int readCode(int index) {
//return the value at the given index
 return rcode[index];
}

void writeCode(int index, int value){
 //Place the given value into rcode array at the given index
   rcode[index] = value;
}

adding functionality to the readCode and writeCode methods to ensure that the bounds of the array are not exceeded are left as an exercise :wink:

Thank you AWOL, I now understand why it wasn't working and have now read up on local variables and the static keyword. You really do learn something new everyday.

mem, thankyou for your help. I have implemented it from your example and seems to work well. I have not yet added the sizeof checking to the array functions but I'm pretty confident that I know how to do that (shouldn't be a problem for the mean time, cause I'm only ever going to write a set number(10) of ints to the array).

Thanks again guys.