feoIII:
Thanks for the answers, of course the code is a simplified one and i gonna use the function in several places inside the loop.
I want to make a function that returns an array not only a number, i want to call once the function and take two or more data from it. I am an arduino user, my programmming skills are limited so I need an example.
I have remake the code whith yoru help and now it looks like this:
int * BuildArray()
{static int MyArray[10]={0,1,2,3,4,5,6,7,8,9};
return MyArray;}
void setup()
{
int TestArray[10]={0,0,0,0,0,0,0,0,0,0};
Serial.begin(9600);
TestArray=BuildArray();
for (int i=0;i<10;i++)
{Serial.println (TestArray[i]);}
}
void loop()
{}
Now there is no error in "int * BuildArray() ", I dont know what "int * " means, but it still has a bug in:
TestArray=BuildArray();
error: incompatible types in assignment of 'int*' to 'int [10]
thanks for your quick answers.
*Moderator edit:* <mark>[</mark><mark>code</mark><mark>]</mark> ... <mark>[</mark><mark>/code</mark><mark>]</mark> tags added. (Nick Gammon)
The int * refers to a pointer to an object. Do a search for c pointers and arrays for more information. Here is one way your code could be implemented without resorting to the use of dynamic allocation--albeit with a few restrictions.
int * BuildArray (void)
{
static int MyArray[10]={0,1,2,3,4,5,6,7,8,9};
return MyArray;
}
void setup()
{
int tmp;
int *TestArray;
Serial.begin(9600);
TestArray = BuildArray();
for (int i=0;i<10;i++)
{
tmp = *(TestArray+i); // Retrieves the content of the array at index i. Depending upon compiler may need to be modified to account for elements of different sizes (i.e. ints, longs, etc...) Look at sizeof function
Serial.println (tmp);
}
}
It is worth learning to work with pointers to objects since they allow C functions to return not just simple data types (bytes, ints, etc...) but more complex ones such as arrays and structs. They are also needed to pass these complex structures to functions