簡體   English   中英

如何在C中訪問結構數組中的結構成員

[英]how to access struct member inside an array of structs in C

我有一個用來獲取某個成員的結構體數組,我遇到的問題是我只想訪問結構體的特定成員,而不是整個結構體本身。 因此,例如,如果我的結構像這樣聲明:

static _Plyr {
 char*  firstName; 
 int age; 
 char* lastName;
}

typedef struct _Plyr Player; 

我有一張桌子...例如

static Player Table[NUM] = {
{"John", 24,  "Wall"}, 
{"Carmelo", 33,  "Anthony"}, 
....
}

我想要一個函數,該函數可以根據一個人的名字返回一個人的姓氏。 所以我有一個* char函數,我知道如何取回整個結構,但是在這種情況下,我只想從特定結構中獲取某個成員,即他們的姓氏...所以我需要修正我的return語句

我的代碼的一部分

char* getLastName(char* string){
 char* first;
 for (int i = 0; i < REGCOUNT; i++){
    first = Table[i].firstName;
    if (strcmp(first, str) == 0){
        return &Table[i].lastName;
    }
  }
}

我已經嘗試過Table[i].lastName, Table[i]->lastName, ...似乎都無法正常工作。 我知道&Table[i]為我提供了結構本身的地址,然后可以從那里訪問它,但是我只是想獲取成員本身而不是整個結構。 感謝您的時間

檢查以下代碼,

typedef struct _Plyr {
    char*  firstName;
    int age;
    char* lastName;
} Player; /* typedef structure  _Plyr into  Player*/


static Player Table[] = { /* Table with NUM of items*/
        {"John", 24,  "Wall"},
        {"Carmelo", 33,  "Anthony"},
        ---------------------------
        ---------------------------
};

#define NUM (sizeof(Table)/sizeof(Player))  /* Maximum number of items in  table */


char* getLastName(char* string){
    char* first;
    for (int i = 0; i < NUM; i++){
        first = Table[i].firstName;
        if (strcmp(first, string) == 0){
            return Table[i].lastName;
        }
    }
}

檢查代碼中添加的注釋。

&Table[i].lastName不是char* ,您必須返回Table[i].lastName才能返回lastName地址。

您必須使用RegTable [i] .lastName。 也許您這樣分配返回值:

str = getLastName(str2);

這是錯誤的。 您必須使用如下的strcpy函數:

strcpy(str,getLastName(str2)); 

如果您使用過strcpy,請不要忘記添加。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM