-
1 Attachment(s)
Is value in array?
Hello there, I am programming Arduino board in Wiring language (C).
I want to use unsigned long array and I want to check if value (element) exists in array.
I have tried solution from: C - If value in array - Stack Overflow that was created for data type float.
But I am unable to get it running for unsigned long data type...
Can somebody help me please what to edit?
Friend told me to don't divide arrays.... But idk why, when for float it was working correctly. I want to use like 6 or 10 values there in array. Is there some other method that I can use that is fast enough?
My original code for Arduino (setup is working like main in pure C):
arrays - Pastebin.com
Output in UART (Serial monitor):
I am awaiting output "ZHODUJE SA", because entry argument (value) is in array... But output is like it is not there.. int returned 0.
Attachment 16322
-
You can't do sizeof on an array once you've passed it to a function.
Or rather, it stops telling you what you want to know.
Code:
unsigned long TEAM_RED[] = {151188, 22222, 33333};
int valueinarray(unsigned long val, unsigned long arr[], size_t len);
unsigned long abc = 33333;
void setup() {
Serial.begin(115200);
Serial.println("Ready");
if (valueinarray(abc, TEAM_RED, sizeof(TEAM_RED) / sizeof(TEAM_RED[0]) )) {
Serial.println("ZHODUJE SA");
} else {
Serial.println("NIE");
}
}
void loop() {
}
int valueinarray(unsigned long val, unsigned long arr[], size_t len)
{
int i;
for (i = 0; i < len; i++)
{
if (arr[i] == val)
return 1;
}
return 0;
}
-
That Stack Overflow solution is wrong: it tries to compute the size with sizeof, but it's invoking sizeof on a pointer instead of an array.
Just have a third parameter that is the number of elements in the array.