I have read some old threads and tested some ideas but my issue still exists so here is what i want: I need a function, what returns a simple array with a fixed size of 181 integer values.
After some tests i have this function:
int *Sonar::scan(int *distances) {
// Scanning
for (int i = 0; i <= 180; i++) {
// Rotates sonar
//this->rotate(i);
// Gets the distance
//distances[i] = this->getDistance();
distances[i] = i;
}
// Returns
return distances;
}
and call it this way:
// Sonar
case 's':
int distances[181];
*distances = sonar.scan(distances);
for (int i = 0; i <= 180; i++) {
Serial.println(String(i) + ": " + String(distances[i]));
}
break;
But i get this result:
0: 1898
1: 1
2: 2
3: 3
4: 4
...
The value of index 0 is corrupted all the time. So what mistake do i made?
Thank you very much for your help: :-)
The first element of the array is being overwritten with the pointer to the array when you do:
*distances = sonar.scan(distances);
That is because you dereference the array with *distances
giving a reference to the first element. You then assign to that with what you return from the scan
method (the pointer to the array).
Just doing:
sonar.scan(distances);
would give the result you expect.
There is no need to return from the method as you are passing the array by a form of reference (a pointer) and that means the array is being changed in place.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.