Reputation: 727
I have this code but I don't know what happen why the result of out
is incorrect any advice please?
int *getarray(int *out)
{
int data[20];
for(int i=0;i<20;i++)
{
data[i]=i;
}
for(int i=0;i<20;i++)
{
out+=data[i];
}
Serial.printf("out inside getarray = %d",out);
return data;
}
void resultdata(){
int *n;
int out;
n=getarray(&out);
Serial.printf("out = %d",out);
}
void setup() {
// Init Serial Monitor
Serial.begin(115200);
resultdata();
}
Upvotes: 0
Views: 75
Reputation: 50831
Two problems:
data
array in getarray
will cease to exist once the getarray
function has finished execution.out
in order to change the out
in resultdata
. Read again the chapter dealing with pointers in your learning material.You probably want something like this:
int *getarray(int *out, int *data)
{
// remove this int data[20];
*out = 0; // you need to dereference the out pointer
// and initialize it to 0
for (int i = 0; i < 20; i++)
{
data[i] = i; // you need to dereference the out pointer
*out += data[i];
}
// I'm not sure why you have this second loop here,
// it looks pretty pointless
for (int i = 0; i < 20; i++)
{
*out += data[i]; // you need to dereference the out pointer
}
Serial.printf("*out inside getarray = %d", *out);
return data;
}
void resultdata(){
int *n;
int out;
int data[20]; // declare the data array here
n = getarray(&out, data); // pass address of the data array
// so that getarray can fill the data array
Serial.printf("out = %d", out);
}
Upvotes: 1