首页 > 解决方案 > 检查两个整数数组是否具有相同的元素,而不管它们的顺序如何

问题描述

此代码将卡片的值存储在arr.value. 然后我尝试检查 arr.value 中的元素是否与 array 具有相同的元素cmpvalues。如果它的元素与数组中的元素不匹配,cmpvalues它应该打印出“错误”并返回 0。但是,即使输入正确,它仍然会打印出错误。一切都编译得很好,我只是找不到错误。

#include <stdio.h>

#define MAXCOLR   14
#define MAXLINE  100
#define MAXCHR  1024   
#define _GNU_SOURCE

typedef struct {
    char color[MAXCOLR];
    int value;
} colorval_t;

int cmpfunc (const void * a, const void * b) {
   return ( *(int*)a - *(int*)b );
}


int main (int argc, char **argv) {

size_t n;
int cmpvalues [] = {
   65,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
   10,
   74,
   81,
   75,
   65,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
   10,
   74,
   81,
   75
};


    size_t ndx = 0;
    char buf[MAXCHR];
    colorval_t arr[MAXLINE] = {{ .color = "" }};

    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) { 
        perror ("file open failed");
        return 1;
    }

    while (ndx < MAXLINE && fgets (buf, MAXCHR, fp)) {
        char c;
        if (sscanf (buf, "%13s %d", arr[ndx].color, &arr[ndx].value) == 2)
            ndx++;
        else if (sscanf (buf, "%13s %c", arr[ndx].color, &c) == 2) {
            arr[ndx].value = c;
            ndx++;
        }
    }
    if (fp != stdin) fclose (fp);   

    for (size_t i = 0; i < ndx; i++)
        printf ("arr[%2zu] : %s %d\n", i, arr[i].color, arr[i].value);




 qsort(arr, 26, sizeof(arr[26]), cmpfunc);
 for( n = 0 ; n < 26; n++ ) {   
      printf("%d ", arr[n].value);
   }



    return 0;



}

输入:

RED A
RED 2
RED 3
RED 4
RED 5
RED 6
RED 7
RED 8
RED 9
RED 10
RED J
RED Q
RED K
BLACK A
BLACK 2
BLACK 3
BLACK 4
BLACK 5
BLACK 6
BLACK 7
BLACK 8
BLACK 9
BLACK 10
BLACK J
BLACK Q
BLACK K

标签: carraysstructintegercompare

解决方案


正确缩进代码表明该函数什么都不做并且总是返回0(除非t1size == 0)。

int all_match( int table1, int table2 , size_t t1size, size_t t2size)
{
    for(size_t t1index = 0; t1index < t1size; t1index++)
    {
        int match = 0;
        for(size_t t2index = 0; t2index < t2size; t2index++)
        {
            match = match ;
            if(match)
            {
                break;          // never happens
            }
        }
        if(!match){
            printf("error");
            return 0;           // always happens
        }
    }
    return 1;
}

请注意,参数tabletable2被忽略。


推荐阅读