Передача Структур у Функції
Функції можуть працювати зі структурами так само, як і зі звичайними змінними:
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; }
Swipe to start coding
Ви керуєте невеликою командою з трьох співробітників, і кожен має погодинну ставку та кількість відпрацьованих годин на тиждень.
Ваше завдання — обчислити середню тижневу зарплату для всієї команди.
У функції calculateWeeklySalary:
- Прийняти структуру типу
Employeeяк параметр. - Отримати доступ до полів
hourlyRateтаhoursWorked. - Перемножити їх для обчислення тижневої зарплати для цього співробітника.
- Повернути обчислену зарплату як
double.
У функції calculateAverageSalary:
- Прийняти три структури
Employeeяк параметри. - Викликати
calculateWeeklySalary()для кожного співробітника, щоб отримати їхню загальну оплату. - Додати всі три зарплати разом.
- Поділити суму на
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
Рішення
Дякуємо за ваш відгук!
single
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you show an example of a function that modifies a structure using a pointer?
How do I return a pointer to a structure created inside a function?
What are the risks of returning pointers to structures created inside functions?
Чудово!
Completion показник покращився до 4.35
Передача Структур у Функції
Свайпніть щоб показати меню
Функції можуть працювати зі структурами так само, як і зі звичайними змінними:
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; }
Swipe to start coding
Ви керуєте невеликою командою з трьох співробітників, і кожен має погодинну ставку та кількість відпрацьованих годин на тиждень.
Ваше завдання — обчислити середню тижневу зарплату для всієї команди.
У функції calculateWeeklySalary:
- Прийняти структуру типу
Employeeяк параметр. - Отримати доступ до полів
hourlyRateтаhoursWorked. - Перемножити їх для обчислення тижневої зарплати для цього співробітника.
- Повернути обчислену зарплату як
double.
У функції calculateAverageSalary:
- Прийняти три структури
Employeeяк параметри. - Викликати
calculateWeeklySalary()для кожного співробітника, щоб отримати їхню загальну оплату. - Додати всі три зарплати разом.
- Поділити суму на
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
Рішення
Дякуємо за ваш відгук!
single