开发者

How to compare integer arrays?

开发者 https://www.devze.com 2023-02-26 13:28 出处:网络
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.

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


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];


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 */ }


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) {
  ...
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号