繁体   English   中英

使用带有结构变量的指针的递归函数中的语法。 它不起作用,我认为主要问题是语法

[英]Syntax in recursive functions using pointers with struct variables. It doesn't work, and I think the main problem is the syntax

我正在做一个菜单,并且我正在尝试执行一个函数,该函数将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: %d\n", 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”,而是“struct client *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”文件中显示二进制数据。 然后,对程序进行调用,说明它按照您的代码设计的精神运行。

从中得出的结论是要注意在函数中传递正确类型的参数,尤其是在使用结构或结构数组时。

希望有帮助。

问候。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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