繁体   English   中英

C如何访问另一个结构中作为结构数组一部分的结构的结构成员?

[英]C How can I acces struct members of a struct that is part of a struct array in another struct?

如果我有以下3个结构:

/*Structures*/
typedef struct team
{
    char* name;
    int playedGames;
    int score;
}team;

typedef struct matchday
{
    char* date;
    team team1;
    team team2;
    team winner; 
    bool isPlayed;
}matchday;

typedef struct sportSeason
{
    matchday *calendar;
    team *ranking;
    int totalMatches;
    int matchesPlayed;
    int remainingMatches;
}sportSeason;

和以下代码:

sportSeason *ptr = malloc(sizeof(sportSeason));

如何在结构中编辑/访问团队或比赛日数组的成员?

例如

ptr->ranking[0]->name = "Team A";

不起作用。

亲切的问候,AggonyAchilles

完整代码(价值):

#define _CRTDDBG_MAP_ALLOC
#define MAX_BUFFER_SIZE 81
#include <stdlib.h>
#include <crtdbg.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

/*Structures*/
typedef struct team
{
    char* name;
    int playedGames;
    int score;
}team;

typedef struct matchday
{
    char* date;
    team team1;
    team team2;
    team winner; 
    bool isPlayed;
}matchday;

typedef struct sportSeason
{
    matchday *calendar;
    team *ranking;
    int totalMatches;
    int matchesPlayed;
    int remainingMatches;
}sportSeason;

/*Function prototypes*/
void initSeason(sportSeason *obj, int n);
void newTeam(team **obj, int *n);
void bufferCheck(char string[]);

int main(void)
{
    char buffer[MAX_BUFFER_SIZE];
    int totalMatches, teams;
    sportSeason *footbalSeason = NULL;

    //Memory allocation
    footbalSeason = malloc(sizeof(sportSeason));

    printf("Welcome to a new season: \n");
    printf("Please enter the following information before registering the teams: \n");
    printf("How many teams are participating: \n");
    fgets(buffer, MAX_BUFFER_SIZE, stdin);
    teams = atoi(buffer);

    initSeason(footbalSeason, teams);


    _CrtDumpMemoryLeaks();
    return 0;
}

void initSeason(sportSeason *obj, int n)
{
    char buffer[MAX_BUFFER_SIZE];

    sportSeason *temp = obj;

    temp->totalMatches = (((n + 1) * n) / 2);
    temp->matchesPlayed = 0;
    temp->remainingMatches = 0;

    printf("Register teams: \n");

    /*Passing the adres of the pointer to the first element of the rank 
      array (team *) */
    newTeam(&(temp->ranking), &n);

}

void newTeam(team **obj, int *n)
{
    char buffer[MAX_BUFFER_SIZE];

    //Allocate memory for all the teams
    obj = malloc((*n) * sizeof(team));

    if (obj == NULL)
    {
        printf("Memory reallocation failed");
    }

    else
    {
        //Add information to struct members
        for (int i = 0; i < (*n); ++i)
        {
            obj[i]->playedGames = 0;
            obj[i]->score = 0;

            printf("\nEnter the team name: ");
            fgets(buffer, MAX_BUFFER_SIZE, stdin);
            bufferCheck(buffer);

            strcpy(obj[i]->name, buffer);

        }
    }
}

分配有问题。 当您发送指向指针的指针时,您基本上会给出该指针的地址,即是否发送了:

  newTeam(&(temp->ranking), &n);

实际分配它,您将需要:在newTeam中:

  void newTeam(team **obj, int *n)
  {
    //blahblah
    (*obj) = (team*) malloc(sizeof(team)* (*n));

为什么? a)p2p是该指针的地址,意味着实际上要引用我们需要的obj指针,请记住malloc返回void,这样更安全。 如果我们将其全部简化为main代码,它将类似于:

int main(){
 sportSeason *ptr = (sportSeason*)malloc(sizeof(sportSeason));
 ptr->totalMatches = ptr->remainingMatches = ptr->remainingMatches = 0;
 ptr->calendar = (matchday*)malloc(4*sizeof(matchday));
 ptr->calendar[0].date = (char*)malloc(sizeof(char) * 4);
 strcpy_s(ptr->calendar[0].date,4,"hi");
 printf("%s", ptr->calendar[0].date);
 //...

为这些操作使用函数绝对是正确的(非常高兴您以模块化方式实现了它!

一个代码,例如 将会:

  int main(void)
   {
      char buffer[MAX_BUFFER_SIZE];
      int teams;
      sportSeason *footbalSeason = NULL;

      //Memory allocation
      footbalSeason = (sportSeason*)malloc(sizeof(sportSeason));

      printf("Welcome to a new season: \n");
      printf("Please enter the following information before registering the teams: \n");
      printf("How many teams are participating: \n");
      fgets(buffer, MAX_BUFFER_SIZE, stdin);
      teams = atoi(buffer);

      initSeason(footbalSeason, teams);

... void initSeason(sportSeason * obj,int n){char buffer [MAX_BUFFER_SIZE];

       sportSeason *temp = obj; //bit unnessery to have temp but w/e

       temp->totalMatches = (((n + 1) * n) / 2);
       temp->matchesPlayed = 0;
       temp->remainingMatches = 0;

       printf("Register teams: \n");

       /*Passing the adres of the pointer to the first element of the rank
      array (team *)<-INCORRECT you pass the address to the pointer it's basicly nothing more - you allocate it */
      newTeam(&(temp->ranking), &n);
      printf("%d\n",temp->ranking[0].playedGames); //will print it just fine

   }

   void newTeam(team **obj, int *n)
   {
      *obj = (team*)malloc(sizeof(team)*(*n));
     obj[0]->playedGames = 0; //for eg.

   }

顺便说一句,当您分配内存时,您实际上必须释放它,所以不要懒惰并使用_crt指令,因为它仅在调试模式下适用,并且并非所有编译器都支持它

所以总而言之:要从p2p(**)访问指针(*),您需要使用: ptr并分配它。 当您使用malloc时,请使用强制转换,因为它会自己返回空,总是垃圾免费,并且不信任任何东西,即使它们位于PC内存中,僵尸也会吞噬您:P

提示:我不知道您是否了解c ++,但这是一种可以帮助您的方法:将您的函数视为所需数据的构造函数,因此,如果您使用纯c编程,请保持将对象构建为最大的函数和函数。销毁对象并清除所有分配并关闭文件/管道,然后关闭。 希望它对您有帮助,如果您愿意随时跟进,我将尽我所能尽我所能

暂无
暂无

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

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