Go Down

Topic: problem returning array from function... (Read 585 times) previous topic - next topic

wrybread

I'm trying to use a function to generate an array. Below is a stripped down version of my code. In the loop, the variable named "pattern" should get an array of numbers from the function generatePattern(). Thanks for any help.


Code: [Select]
int pattern_local[] = {1, 2};
int pattern[] = {3, 4};


void setup()
{
 Serial.begin(9600);
}

void loop()
{
 pattern = generatePattern();
}



int generatePattern()
{
int pattern_local[] = {1, 2};
return pattern_local;
}


This errors out with:
Code: [Select]

In function 'void loop()':
error: incompatible types in assignment of 'int' to 'int [2]' In function 'int generatePattern()':


Can anyone point me in the right direction?

BetaDelta

The array contains two integers and you cannot assign them to a single integer. so you need to choose one value in the array to assign or do some maths!

/me
"C++ : Where friends have access to your private members." - Gavin Russell Baker

halley

#2
Apr 15, 2009, 04:01 pm Last Edit: Apr 15, 2009, 04:01 pm by halley Reason: 1
Don't write functions to "return an array."

Write functions that can fill out a given array.  Remember to tell the function how long the array is.

Code: [Select]
#define PATTERN_LENGTH 2

int the_pattern[PATTERN_LENGTH];

void setup()
{
   Serial.begin(9600);
}

void loop()
{
   generatePattern(the_pattern, PATTERN_LENGTH);
}

void generatePattern(int pattern[], int length)
{
   int value = 1;
   for (int i = 0; i < length; i++)
   {
       pattern[i] = value;
       value++;
   }
}

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