C - 如何通过引用将结构指针数组传递给函数

C - How to pass struct pointer array to a function by reference

我有这个结构:

typedef struct {
    char name[31];
    int played;
    int won;
    int lost;
    int tie;
    int points;
} Player;

这个函数用文件中的数据填充结构数组:

int load(Player *players[], int max_players, int *player_count)
{
    static const char filename[] = "players.txt";
    FILE *file = fopen(filename, "r");

    if (file != NULL)
    {
        char line[128]; 

        players = malloc(max_players * sizeof *players);

        while (1) /* read until end of file */
        {

            players[*player_count] = malloc(sizeof(Player));

            if (*player_count < max_players && fgets(players[*player_count]->name, sizeof players[*player_count]->name, file) != NULL)
            {
                fscanf(file, "%d", &players[*player_count]->played);    // read played
                fscanf(file, "%d", &players[*player_count]->won);       // read won 
                fscanf(file, "%d", &players[*player_count]->lost);      // read lost 
                fscanf(file, "%d", &players[*player_count]->tie);       // read tie 
                fscanf(file, "%d", &players[*player_count]->points);    // read points 
                fgets(line, sizeof line, file);                         // read new line

                // increase player count
                *player_count += 1;
            }
            else
            {
                break;
            }
        }

        fclose(file);
    }
    else
    {
        return 0;
    }
    return 1;
}

现在我在通过传递玩家作为参考来调用它时遇到问题,以便在调用端反映玩家的更新数据。

下面是我的调用代码,我认为有问题:

Player *players[MAX_PLAYERS] = { NULL };
int playerCount = 0;
load(players, MAX_PLAYERS, &playerCount);

当我调试代码时,球员的数组被填充到函数中,但当它 returns 返回时,球员的值仍然为空。

如有任何帮助,我们将不胜感激。

您正在覆盖局部变量 players

从您不需要的函数中删除下面的行。

   players = malloc(max_players * sizeof *players);|

因为您已经在 main 中有了指针数组。


您不需要 Player 类型的指针数组,您只需要 Player

类型的数组
Player *players;
load(&players, MAX_PLAYERS, &playerCount);

并在 load 函数中。

int load(Player **players, int max_players, int *player_count)
{
    static const char filename[] = "players.txt";
    FILE *file = fopen(filename, "r");

    if (file != NULL)
    {
        char line[128]; 

        (*players) = malloc(max_players * sizeof **players);

        while (1) /* read until end of file */
        {


            if (*player_count < max_players && fgets((*players)[*player_count].name, sizeof (*players)[*player_count].name, file) != NULL)
            {
                fscanf(file, "%d", &(*players)[*player_count].played);    // read played
                fscanf(file, "%d", &(*players)[*player_count].won);       // read won 
                fscanf(file, "%d", &(*players)[*player_count].lost);      // read lost 
                fscanf(file, "%d", &(*players)[*player_count].tie);       // read tie 
                fscanf(file, "%d", &(*players)[*player_count].points);    // read points 
                fgets(line, sizeof line, file);                         // read new line

                // increase player count
                *player_count += 1;
            }
            else
            {
                break;
            }
        }

        fclose(file);
    }
    else
    {
        return 0;
    }
    return 1;
}

C 不支持通过引用传递变量。

我只是保持简单。您的函数应如下所示:

int load(Player *players, int max_players, int *player_count)
{
    static const char filename[] = "players.txt";
    FILE *file = fopen(filename, "r");

    if (file != NULL)
    {
        char line[128]; 

        while (!feof(file ) && !ferror(file )) /* read until end of file */
        {
            fscanf(file, "%d", &players[*player_count].played);    // read played
            fscanf(file, "%d", &players[*player_count].won);       // read won 
            fscanf(file, "%d", &players[*player_count].lost);      // read lost 
            fscanf(file, "%d", &players[*player_count].tie);       // read tie 
            fscanf(file, "%d", &players[*player_count].points);    // read points 
            fgets(line, sizeof line, file);                         // read new line

            // increase player count
            *player_count += 1;
        }

        fclose(file);

        return 1;
    }

    return 0;
}

和主要:

int main ()
{
    Player players[MAX_PLAYERS] = { NULL };
    int playerCount = 0;
    load(players, MAX_PLAYERS, &playerCount);
    printf("");
}

以下建议代码:

  1. 尚未编译,因为 OP 没有 post 最小的、完整的、可验证的示例
  2. 正确传递参数
  3. 正确检查错误
  4. 执行所需的功能
  5. 展示了如何在main()
  6. 中初始化指针
  7. 显示如何更新 main()
  8. 中的指针
  9. 按照计划不可恢复的错误导致代码输出到stderr所有的错误信息,然后退出
  10. 遵循 'typical' 成功返回值“0”
  11. 确保在 main() 中将所有分配的内存指针传递给 free() 以避免内存泄漏

现在,建议的代码修改:

regarding:

    typedef struct 
    {
        char name[31];
        int played;
        int won;
        int lost;
        int tie;
        int points;
    } Player;

this anonymous struct will be very difficult to display 
the individual fields via a debugger,
because debuggers use the 'tag' name of the struct 
to reference the individual fields


in main function: Notice only declaring a pointer initialized to NULL,
then passing the address of the pointer to the function: `load()`

    Player *players =  NULL;
    int playerCount = 0;
    load(&players, &playerCount);  

notice the double '**' on the 'players' parameter
This enables the sub function to modify the pointer field in the caller

    int load(Player **players, int *player_count)
    {
        static const char filename[] = "players.txt";

        // it is poor programming practice to name a variable the
        // same as a struct, so changed `file` to `fp`
        FILE *fp = fopen(filename, "r");
        if( !fp )
        {
            perror( "fopen to read players.txt failed" );
            exit( EXIT_FAILURE );
        }

        // implied else, fopen successful

        // increased the size of the input buffer `line[]` for safety
        char line[1024]; 

        // note: used `calloc()` so when cleaning up from error
        //       no need to check if a specific entry in the 'player'
        //       array is used.  `free()` handles a NULL parameter just fine
        *players = calloc( MAX_PLAYERS, sizeof(Player*) );
        if( !*players )
        {
            perror( "calloc for array of pointers to players failed" );
            exit( EXIT_FAILURE );
        }

        // implied else, malloc successful

        /* read until end of file  or array full*/
        while (*player_count < MAX_PLAYERS && fgets(line, sizeof line, fp)) 
        {
            (*players)[*player_count] = malloc(sizeof(Player));
            if( !(*players)[ *player_count ] )
            {
                perror( "malloc for individual player failed" );
                for( int i=0; i<MAX_PLAYERS; i++ )
                {
                    free( (*players)[i] );
                }
                free( *players ); 
                exit( EXIT_FAILURE );
            }

            // implied else, malloc successful

            if( sscanf( line, "%d %d %d %d %d", 
                players[*player_count]->played,    // read played
                players[*player_count]->won,       // read won 
                players[*player_count]->lost,      // read lost 
                players[*player_count]->tie,       // read tie 
                players[*player_count]->points) != 5 )   // read points 
            {
                fprintf( stderr, "extraction of player fields failed\n" );
                exit( EXIT_FAILURE );
            }


            // increase player count
            (*player_count) += 1;
        }

        fclose(file);

        return 0;
    }

我认为你的函数应该这样写

int func(int ***players){
    *players=new int* [MAXSIZE];
    //use this if use c
    // *players=(int**)malloc(sizeof(int*)*MAXSIZE);
    for(int i=0;i<MAXSIZE;i++){
        *(*players+i)=new int[2];
        // *(*players+i)=(int*)malloc(sizeof(int)*2); 
        //2 is test can choose every number if your computer allow
    }
}

你的主应该喜欢这个主:

int main(){

    int **players=nullptr;
    func(&players);
    //use follow if you must delete 
    for(int i=0;i<MAXSIZE;i++){
        delete players[i];
    }
    delete players;
    return 0;
}
typedef struct {    int played;} Player;


void load(Player* &players, int max_players, int &player_count)
{
    players = (Player*)malloc(max_players * sizeof(Player));

    for (int i = 0; i < max_players; i++)
    {
        players[i].played = i;
        player_count++;
    }
}

int main()
{
    const int MAX_PLAYERS=3;
    Player* players=  NULL ;
    int playerCount = NULL;
    load(players, MAX_PLAYERS, playerCount);

    //...
    free(players);
}
  • 结构:
typedef struct Foo {
  int x;
} Foo;

函数:

void f(Foo **foo) {
  foo[0]->x = 2021;                // already allocate in main
  foo[1]    = malloc(sizeof(Foo)); // not locate yet
  foo[1]->x = 2022;
}
  • 主要内容:
int main() {
  Foo **foo = malloc(100 * sizeof(Foo *)); // foo[10]

  foo[0]    = malloc(sizeof(Foo));         // must allocate before using
  foo[0]->x = 2020;                        // assing 2021 to foo[0].x must use arrow for pointer

  f(foo);
  foo[1]->x = 2024;                        // already allocate in function f();

  printf("main: value of x: %d\n", foo[0]->x);
  printf("main: value of x: %d\n", foo[1]->x);
}
  • 输出:
$ gcc test.c && ./a.out
value of x: 2021
value of x: 2024