C構造体の文字列フィールドを操作するにはどうすればいいですか? 質問する

C構造体の文字列フィールドを操作するにはどうすればいいですか? 質問する

C で単リンク リストに基づくデータベースを作成するときに問題があります。これは、リンク リストの概念ではなく、構造体自体の文字列フィールドが原因です。

これは C での割り当てであり、私が知る限り (私は初心者です)、C は 'string' をデータ型として認識しません。

私の構造体コードは次のようになります:

typedef struct 
{
  int number;
  string name;
  string address;
  string birthdate;
  char gender;
} patient;

typedef struct llist
{
  patient num;
  struct llist *next;
} list;

次のように、文字列自体の構造体を作成して、その構造体内で文字列を使用できるようにしたいと考えていました。

typedef struct string 
{ 
  char *text;
} *string;

次に、malloc()文字列型(charの配列)の新しいデータを作成する必要があるときに、それぞれを実行します。

typedef struct string
{
  char *text;
} *string;

int main()
{
    int length = 50;
    string s = (string) malloc(sizeof string);
    s->text = (char *) malloc(len * sizeof char);
    strcpy(s->text, patient.name->text);
}

誰かこれを理解するのを手伝ってくれませんか?
ありがとうございます。

ベストアンサー1

文字列とメモリの割り当てについて:

C の文字列は単なる のシーケンスなのでchar、文字列データ型を使用したい場合はどこでもchar *または配列を使用できます。char

typedef struct     {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} patient;

次に、構造体自体と各文字列にメモリを割り当てる必要があります。

patient *createPatient(int number, char *name, 
  char *addr, char *bd, char sex) {

  // Allocate memory for the pointers themselves and other elements
  // in the struct.
  patient *p = malloc(sizeof(struct patient));

  p->number = number; // Scalars (int, char, etc) can simply be copied

  // Must allocate memory for contents of pointers.  Here, strdup()
  // creates a new copy of name.  Another option:
  // p->name = malloc(strlen(name)+1);
  // strcpy(p->name, name);
  p->name = strdup(name);
  p->address = strdup(addr);
  p->birthdate = strdup(bd);
  p->gender = sex;
  return p;
}

必要なメモリが数個だけであればpatient、実際に必要なメモリよりも多くのメモリを割り当てるという犠牲を払ってメモリ管理を回避することができます。

typedef struct     {
  int number;
  char name[50];       // Declaring an array will allocate the specified
  char address[200];   // amount of memory when the struct is created,
  char birthdate[50];  // but pre-determines the max length and may
  char gender;         // allocate more than you need.
} patient;

リンクリストの場合:

一般に、リンク リストの目的は、順序付けられた要素のコレクションにすばやくアクセスできるようにすることです。 にllistという要素num(おそらく患者番号を含む) が含まれている場合、実際の 自体を保持するための追加のデータ構造が必要になりpatient、毎回患者番号を検索する必要があります。

代わりに、宣言すれば

typedef struct llist
{
  patient *p;
  struct llist *next;
} list;

各要素には構造体への直接ポインターが含まれておりpatient、次のようにしてデータにアクセスできます。

patient *getPatient(list *patients, int num) {
  list *l = patients;
  while (l != NULL) {
    if (l->p->num == num) {
      return l->p;
    }
    l = l->next;
  }
  return NULL;
}

おすすめ記事