Search code examples
carduino-idearduino-c++arduino-esp32

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

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