簡體   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