我正在做一个菜单,我正在尝试做一个函数,该函数将在struct中查找特定的ID,如果它找到了匹配的ID,它将返回ID编号的位置,否则它将返回NULL。任何帮助都是受欢迎的,它甚至不会给我任何回报,只是编译错误。
struct client {
int id;
} cli[10]; // Let's say I already have cli.id = {1, 2, 3}
int idPosition(FILE *ptn1, int *arr, int idWanted, int i, int top);
int main() {
int id, position;
FILE *fp;
fp = fopen("clients.txt","rb+"); // I should have the cli.id = {1,2,3}
printf("ID: ");
scanf("%i", &id); // Let's suppose I insert a 3
position = idPosition(*fp, *cli, id, 0, 10); // I should get a 2, which would the position of the 3
}
int idPosition(FILE *ptn1, int *arr, int idWanted, int i, int top) {
fread(&arr[i],sizeof(arr[i]),1, ptn1); // ptn1 is pointing to FILE *fp which already fp = fopen("...","rb+");
if ((*(arr+i)).id == idWanted)
return i;
else if (idWanted == top)
return NULL;
return idPosition(ptn1, arr, idWanted, i+1, top);
}
我试用了您的代码,但实际上它无法编译。问题出现在ID位置函数的参数集中。即使ID结构只包含一个整数,函数也不能通过整数数组指针引用结构数组。有了这个,我构建了一个简单的文件,其中包含数字1-10的ID,然后对代码进行了一些调整。以下是经过调整的代码的副本。
#include <stdio.h>
#include <stdlib.h>
struct client {
int id;
} cli[10];
int idPosition(FILE *ptn1, struct client *arr, int idWanted, int i, int top); /* The second parameter needed to reference the structure array even though it only holds an integer */
int main(void) {
int id, position;
FILE *fp;
fp = fopen("clients.txt","rb+"); // I should have the cli.id = {1,2,3}
printf("ID: ");
scanf("%i", &id); // Let's suppose I select a 3
position = idPosition(fp, cli, id, 0, 10); // I should get a 2, which would the position of the 3
printf("Position: %dn", position);
}
int idPosition(FILE *ptn1, struct client *arr, int idWanted, int i, int top) {
fread(&arr[i],sizeof(arr[i]),1, ptn1); // ptn1 is pointing to FILE *fp which already fp = fopen("...","rb+");
if ((*(arr+i)).id == idWanted)
return i;
else
if (idWanted > top)
return NULL;
else
return idPosition(ptn1, arr, idWanted, i+1, top);
}
要指出的关键位是";idPosition";作用代替";int*arr";第二个参数的定义是"0";结构客户端*arr";。这与通过";cli"数组。
当我测试这个时,这是我在终端上的结果。
@Una:~/C_Programs/Console/Recursion/bin/Release$ hexdump clients.txt
0000000 0001 0000 0002 0000 0003 0000 0004 0000
0000010 0005 0000 0006 0000 0007 0000 0008 0000
0000020 0009 0000 000a 0000
0000028
@Una:~/C_Programs/Console/Recursion/bin/Release$ ./Recursion
ID: 3
Position: 2
第一个命令只是将二进制数据呈现在";client.txt";文件然后,对程序进行了调用,说明它是按照代码设计的精神运行的。
这样做的好处是要注意在函数中传递正确类型的参数,尤其是在使用结构或结构数组时。
希望能有所帮助。
谨致问候。