c言語structにおける文字列タイプのメンバー変数は、charポインタの定義を使用することを推奨しない。

1190 ワード

たとえば、下記のコード:
struct pnames {
    char * first;
    char * last;
};

struct pnames tt;

scanf("Please enter the first name: %s", tt.first);
scanf("Please enter the last name: %s", tt.last);
struct pnamesタイプの変数ttが定義されているため、この変数は初期化されていません。したがって、firstは、lastの値がメモリ内の任意の領域を指す可能性がある。後にscanfがfirst、lastが指すメモリ領域を修正すれば、思わぬ問題を引き起こすかもしれない。char配列を使うなら問題ないです。例えば、
struct pnames {
    char first[20];
    char last[20];
};

struct pnames tt;

scanf("Please enter the first name: %s", tt.first);
scanf("Please enter the last name: %s", tt.last);
このとき変数ttを定義すると、firstとなり、lastは固定された空間を割り当てて、ユーザがscanfを通して入力したことを保存するために使用される。これは安全性を保証します。
ある場合、私たちはstructで文字ポインタを使うことができます。つまり、malloc()と結合して、ユーザーが入力した文字の長さに応じて、同じサイズのメモリを申請して保存します。たとえば:
struct pnames {
    char * first;
    char * last;
};

struct pnames tt;

char first[20];
char last[20];

scanf("Please enter the first name: %s", first);
scanf("Please enter the last name: %s", last);

tt.first = (char *) malloc(strlen(first)+1);
tt.last = (char *) malloc(strlen(last)+1);
しかし、このようにして、必ずfreeでメモリを解放してください。そうしないと、プログラムが終了した時にメモリが漏れてしまいます。