Khali
Khali

Reputation: 1

How to compare integer arrays?

I have four sensors (sen0-sen3) which return either 1 or 0 and I am making an array of values using sprintf. Then I am trying to compare them with 0000 or 1000 and so on.

My Problem is even if the value of sen_array is 1000, it never goes into the else if condition (straight to else condition).

char sen_array[4];

sprintf(sen_array,"%d%d%d%d",sen0,sen1,sen2,sen3);
if(strcmp("0000",sen_array)==0)
{
    motor_pwm((156*(0.20).),(156*(0.20)));
}
else if(strcmp("1000",sen_array)==0)
{
    motor_pwm((156*(0.40)),(156*(0.40)));
}
else
{
    motor_pwm((156*(0.80)),(156*(0.80)));
}

Upvotes: 0

Views: 2880

Answers (4)

ildjarn
ildjarn

Reputation: 62975

What you're seeing is an artifact of memory corruption. The problem is that you've declared sen_array to be a char[4], which doesn't leave room for a terminating null. Change sen_array to:

char sen_array[5];

Upvotes: 4

jack_carver
jack_carver

Reputation: 1526

I think sen_array should be atleast 5 chars long and unless you are using the sen_array for something else, A better and faster way is to do

int res = 1000*sen0+100*sen1+10*sen2+sen3;

And use this to compare.

Upvotes: 1

Erik
Erik

Reputation: 91270

Your sen_array should be at least 5 chars long - to make room for a 0-terminator.

char sen_array[4];
sprintf(sen_array, "%d%d%d%d", 1, 2, 3, 4);

The above writes '1' '2' '3' '4' '\0' to sen_array - overflowing it and perhaps affecting a nearby variable

Use char sen_array[5];

A perhaps better solution would be to work with an integer:

int sa = sen0 * 1000 + sen1 * 100 + sen2 * 10 + sen3;

if (sa == 1000) {
  ...
} else if (sa == 1001) {
  ...
}

Upvotes: 1

Rune Aamodt
Rune Aamodt

Reputation: 2611

Not using STL, I think the best way to compare integer arrays is using the memcmp function which compares blocks of memory.

int sen_array1[] = { 1, 2, 3, 4 } ;
int sen_array2[] = { 1, 2, 3, 4 } ;
if(memcmp(sen_array1, sen_array2, sizeof(int)*4) == 0) { /* do something */ }

Upvotes: 2

Related Questions