Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill an array by extracting a partial array

Tags:

arrays

c

I was trying to fill an array,xlow, by extracting some elements from an array called exit_2. By making the array xlow, I wanted access specific elements of it but the code gives some weird numbers.

#include <stdio.h>
int main()
{
 int exit_1[4]={3,0,7,11},exit_2[4]={90,164,232,328},xlow[2],i;
 for(i=0;i<4;++i){
    if(exit_1[i]<7){
        xlow[2]=exit_2[i];
    }
}
 printf("%d",xlow[0]);
 return 0;
}

Thank you your help

like image 411
yushay bohra Avatar asked Mar 21 '26 06:03

yushay bohra


1 Answers

xlow[2]=exit_2[i];

As you see you are initializing xlow[2]. xlow[0] is still uninitialized and using uninitialized variables lead to undefined behavior.

int j=0;
 for(i=0;i<4;++i){
    if(exit_1[i]<7){
        if(j>1)
        break;
        else
        xlow[j++]=exit_2[i];
    }
}
like image 107
Gopi Avatar answered Mar 23 '26 18:03

Gopi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!