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

时间:2016-07-17 16:50:22

标签: c arrays dynamic 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);

        }
    }
}

1 个答案:

答案 0 :(得分:0)

出现分配问题。 当您向指针发送指针时,您基本上会给出该指针的地址 意味着你发送了:

  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时请使用cast,因为它返回void 总是自己免费并且不相信任何东西,僵尸可以吃掉你,即使他们在电脑记忆中:P

提示:我不知道您是否了解c ++,但这里有一种方法可以帮助您: 将您的函数视为您想要的数据的构造函数,因此如果您使用纯c编程,将构建对象的函数保持在最大程度,并保留破坏对象的函数并清除所有分配和关闭文件/管道等等。希望它能帮助你,如果没有随意请求跟进,我会尽力回答我的能力