Go Down

Topic: return an array from a function (Read 928 times) previous topic - next topic

I want to return an array from a function. But I get the follow error :
In function 'int getRGB()':
error: invalid conversion from 'int*' to 'int' In function 'void loop()':

Writing : int getRGB()[3] doesn't seem to work :
error: 'getRGB' declared as function returning an array In function 'int getRGB()':

I searched in the forum but couldn't find a syntax for it.

Code example :

Code: [Select]

int colorsRGB[3];
int colors_1[3];
int colors_2[3];

int getRGB()
{ colorsRGB[0]=255;
  colorsRGB[1]=0;
  colorsRGB[2]=0;  
  return colorsRGB;
}

colors_1=getRGB();
colors_2=getRGB();




mellis

You're getting into a relatively tricky area, touching on pointers, memory management, etc.  The easiest solution is probably to pass an array into the function and simply write the result to it (rather than trying to return the array).  That is:

Code: [Select]

int colors1[3];

void getRGB(int colors[3])
{
 colors[0] = 255;
 colors[1] = 0;
 colors[2] = 0;
}

void loop()
{
 getRGB(colors1);
}

Ok, this works. I thought you always had to return someting to put a value into an array.

Would you mind to explain me how this works ( just curious ) ? How gets the data into the colors1 array ? Does it have to do with the fact that an array is a kind of a pointer ?

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy