Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the output is incorrect

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Two problems:

  • The data array in getarray will cease to exist once the getarray function has finished execution.
  • You need to dereference 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);   
} 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading