Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 構造体を関数に渡す | ポインタと構造体の操作
C構造体
セクション 2.  5
single

single

構造体を関数に渡す

メニューを表示するにはスワイプしてください

関数は、通常の変数と同様に構造体を扱うことが可能

main.c

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

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

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関数内では:

  1. Employee型の構造体をパラメータとして受け取ります。
  2. hourlyRatehoursWorkedのフィールドにアクセスします。
  3. それらを掛け合わせて、その従業員の週給を計算します。
  4. 計算した給与をdouble型で返します。

calculateAverageSalary関数内では:

  1. 3つのEmployee構造体をパラメータとして受け取ります。
  2. 各従業員に対してcalculateWeeklySalary()を呼び出し、それぞれの給与を取得します。
  3. 3人分の給与を合計します。
  4. 合計を3.0で割り、平均週給を算出します。
  5. この平均値をdouble型で返します。

Example

Employee NameHourly RateHours WorkedWeekly Salary
Alice Johnson22.540900.00
Bob Smith18.038684.00
Carol White25.0421050.00

Average Weekly Salary: 878.00

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  5
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt