简体   繁体   中英

No output during array matching

I am trying to check two arrays if they are equal are not, if they are not equal print the corresponding text. I did this but i don't get any output or errors from this code. what did i do wrong in this?

typedef struct payl{
    int arrayp[5] = {1,2,3,4,5};
}payl;
typedef struct expected{
    int arraye[5] = {1,2,3,4,6};
}expected;

int main()
{
    payl* pay;
    expected* Ez;
    int itr = (sizeof(pay->arrayp)/sizeof(pay->arrayp[0]));
    int eitr = (sizeof(Ez->arraye)/sizeof(Ez->arraye[0]));
    for(int i=0; i>itr; i++){
        for(int j=0; j>eitr; j++){
            if(pay->arrayp[i] != Ez->arraye[j]){
                cout<<"incorret matching"<<pay->arrayp[i]<<"!="<<Ez->arraye[j]<<endl;
            }
        }
    }
    return 0;
}

I know they are other ways to do this, but i want to know what i did wrong in this. Thank you.

First of all, pay and Ez are pointers, but you never make them point anywhere valid. This is undefined behavior, and will likely result in a segmentation fault or do something different entirely. Change this:

payl* pay;
expected* Ez;

To this:

payl* pay = new payl;
expected* Ez = new expected;

And don't forget to delete them in the end:

delete pay;
delete expected;

Also, your comparisons don't work this way. Instead of this:

for(int i=0; i>itr; i++){
   for(int j=0; j>eitr; j++){ 

You should wap that > around and do this instead:

for (int i = 0; i < itr; i++) {
    for (int j = 0; j < eitr; j++) {

With those changes, it correctly prints every instance of every element in each array that's not the same as a different element. Which means not just that last one where there's a 5 in one and a 6 in another. That's not how you check whether two arrays are equal. Instead, the loop should look like this:

for (int i = 0; i < itr; i++) {
    if (pay->arrayp[i] != Ez->arraye[i]) {
        cout<<"incorret matching"<<pay->arrayp[i]<<"!="<<Ez->arraye[j]<<endl;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM