3

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

2 Answers 2

1
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];
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You will get weird numbers because xlow[0] is never written to or initialized, you only ever write to xlow[2].

That means when you do printf("%d",xlow[0]);, the program will just print whatever random values are in the memory location of xlow[0].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.