セクション 2. 章 5
single
構造体を関数に渡す
メニューを表示するにはスワイプしてください
関数は、通常の変数と同様に構造体を扱うことが可能
main.c
123456789101112131415161718192021#include <stdio.h> // structure definition typedef struct { char name[50]; } Person; // function to display information about a person void printPerson(Person p) { printf("Name: %s\n", p.name); } int main() { // creating a structure and initializing its values Person person1 = {"John"}; // call a function to display information about a person printPerson(person1); return 0; }
関数が構造体と「やり取り」する、例えば既存の構造体のフィールドを変更する場合、関数は構造体へのポインタを受け取る必要がある
main.c
12345678910111213141516171819202122232425262728293031#include <stdio.h> // structure definition typedef struct { char symbol; }Example; // function for changing the values of structure fields via a pointer void changePoint(Example* ptr, int newSymbol) { // check for NULL pointer if (ptr != NULL) { ptr->symbol = newSymbol; } } int main() { // create the Example structure and a pointer Example ptr1 = {'H'}; Example* ptr = &ptr1; printf("Old symbol: %c | %p\n", ptr1.symbol, &ptr1); // use function to change the field of structures changePoint(ptr, 'y'); printf("New symbol: %c | %p\n", ptr1.symbol, &ptr1); return 0; }
構造体は関数内で作成することができ、そのような構造体は関数がその構造体へのポインタを返す場合、(ローカルではなく)関数の外部でも「生存」することができます。
main.c
1234567891011121314151617181920212223242526272829303132#include <stdio.h> #include <stdlib.h> // structure definition typedef struct { int value; }Example; // function creates a structure with the given field Example* CreateStruct(int setVal) { Example* ptr = (Example*)malloc(sizeof(Example)); // check for successful memory allocation if (ptr != NULL) { ptr->value = setVal; } return ptr; } int main() { // use function to create structure Example* ptrToStruct = CreateStruct(23); printf("Value inside struct: %d", ptrToStruct->value); free(ptrToStruct); // free memory return 0; }
タスク
スワイプしてコーディングを開始
あなたは3人の従業員からなる小規模なチームを管理しています。それぞれの従業員には時給と1週間あたりの労働時間があります。 あなたの課題は、チーム全体の平均週給を計算することです。
calculateWeeklySalary関数内では:
Employee型の構造体をパラメータとして受け取ります。hourlyRateとhoursWorkedのフィールドにアクセスします。- それらを掛け合わせて、その従業員の週給を計算します。
- 計算した給与を
double型で返します。
calculateAverageSalary関数内では:
- 3つの
Employee構造体をパラメータとして受け取ります。 - 各従業員に対して
calculateWeeklySalary()を呼び出し、それぞれの給与を取得します。 - 3人分の給与を合計します。
- 合計を
3.0で割り、平均週給を算出します。 - この平均値を
double型で返します。
Example
| Employee Name | Hourly Rate | Hours Worked | Weekly Salary |
|---|---|---|---|
| Alice Johnson | 22.5 | 40 | 900.00 |
| Bob Smith | 18.0 | 38 | 684.00 |
| Carol White | 25.0 | 42 | 1050.00 |
Average Weekly Salary: 878.00
解答
すべて明確でしたか?
フィードバックありがとうございます!
セクション 2. 章 5
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください