Pages: [1]   Go Down
Author Topic: return an array from a function  (Read 773 times)
0 Members and 1 Guest are viewing this topic.
Enschede - The Netherlands
Offline Offline
Jr. Member
**
Karma: 0
Posts: 75
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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();



Logged

Forum Administrator
Cambridge, MA
Offline Offline
Faraday Member
*****
Karma: 12
Posts: 3538
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
int colors1[3];

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

void loop()
{
  getRGB(colors1);
}
Logged

Enschede - The Netherlands
Offline Offline
Jr. Member
**
Karma: 0
Posts: 75
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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 ?
Logged

Pages: [1]   Go Up
Jump to: