C の構造体ポインター
構造体ポインタは、構造体ポインタを格納するメモリブロックのアドレスを指すポインタとして定義されます。 構造 構造体ポインタとして知られています。リンクされたリスト、ツリー、グラフなどの複雑なデータ構造は、構造ポインターを使用して作成されます。構造体ポインタは、変数を構造体変数に指すことによって、メモリ内の構造体のアドレスを伝えます。
例:
C
// C program to demonstrate structure pointer> #include> struct> point {> > int> value;> };> int> main()> {> > struct> point s;> > > // Initialization of the structure pointer> > struct> point* ptr = &s;> > return> 0;> }> |
上記のコードでは s は構造体ポイントのインスタンスであり、 ptr は構造体ポイントのアドレスを格納しているため、構造体ポインタです。
ポインタを使用した構造体メンバーへのアクセス
構造体ポインターを使用して構造体のメンバーにアクセスするには、次の 2 つの方法があります。
- (*) アスタリスクまたは間接演算子と (.) ドット演算子を使用します。
- ( -> ) 矢印演算子の助けを借りて。
以下は、ドット演算子の助けを借りて構造体ポインターを使用して構造体のメンバーにアクセスするプログラムです。
C
// C Program to demonstrate Structure pointer> #include> #include> struct> Student {> > int> roll_no;> > char> name[30];> > char> branch[40];> > int> batch;> };> int> main()> {> > struct> Student s1;> > struct> Student* ptr = &s1;> > s1.roll_no = 27;> > strcpy> (s1.name,> 'Kamlesh Joshi'> );> > strcpy> (s1.branch,> 'Computer Science And Engineering'> );> > s1.batch = 2019;> > printf> (> 'Roll Number: %d
'> , (*ptr).roll_no);> > printf> (> 'Name: %s
'> , (*ptr).name);> > printf> (> 'Branch: %s
'> , (*ptr).branch);> > printf> (> 'Batch: %d'> , (*ptr).batch);> > return> 0;> }> |
出力:
1
以下は、Arrow 演算子の助けを借りて構造体ポインターを使用して構造体のメンバーにアクセスするプログラムです。このプログラムでは、構造変数を含む Structure Student を作成しました。 Student 構造には、roll_no、名前、ブランチ、およびバッチがあります。
C
// C Program to demonstrate Structure pointer> #include> #include> // Creating Structure Student> struct> Student {> > int> roll_no;> > char> name[30];> > char> branch[40];> > int> batch;> };> // variable of structure with pointer defined> struct> Student s, *ptr;> int> main()> {> > ptr = &s;> > // Taking inputs> > printf> (> 'Enter the Roll Number of Student
'> );> > scanf> (> '%d'> , &ptr->roll_no);>>' );> > scanf> (> '%s'> , &ptr->名前);>> );> > scanf> (> '%s'> , &ptr->ブランチ);>>' );> > scanf> (> '%d'> , &ptr->バッチ);>> );> > printf> (> 'Roll No: %d
'> , ptr->roll_no);>>' , ptr->名前);>> , ptr->ブランチ);>>' , ptr->バッチ);>> |