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