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

时间:2019-06-16 02:39:02

标签: c pointers struct pass-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);

当我调试代码时,玩家的数组会被填充到函数中,但是当它返回时,玩家的值仍然为空。

任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:1)

您正在覆盖局部变量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;
}

答案 1 :(得分: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("");
}

答案 2 :(得分:0)

以下建议的代码:

  1. 未编译,因为OP没有发布最小,完整,可验证的示例
  2. 正确传递参数
  3. 正确检查错误
  4. 执行所需的功能
  5. 显示如何在main()中初始化指针
  6. 显示如何更新main()中的指针
  7. 遵循以下计划:不可恢复的错误导致代码将所有错误信息输出到stderr,然后退出
  8. 遵循“典型”返回值“ 0”以获取成功
  9. 请确保在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;
    }

答案 3 :(得分: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;
}

答案 4 :(得分: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);
}