此代码将卡的值存储在arr.value
中。然后我尝试检查 arr.value 中的元素是否与数组 cmpvalues
具有相同的元素。如果元素与数组中的元素不匹配cmpvalues
则应打印出"error"并返回 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 %dn", 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
正确缩进代码表明函数不执行任何操作,并且始终返回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;
}
请注意,table
和table2
参数将被忽略。
以下匹配函数可以解决问题:
int all_match( colorval_t *table1, colorval_t *table2 , size_t t1size, size_t t2size)
{
for(size_t t1index = 0; t1index < t1size; t1index++)
{
for(size_t t2index = 0; t2index < t2size; t2index++)
{
if (table1[t1index].value==table2[t2index].value
&& strcmp(table1[t1index].color, table2[t2index].color)==0)
break;
}
if (t2index >= t2size) {
printf("error");
return 0;
}
}
return 1;
}