Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Arrays with Structs | Understanding Structs and Memory
/
C Structs
セクション 3.  4
single

single

bookArrays with Structs

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

Creating an array from structures is no different from creating an array with other data types.

Accessing the elements of such an array is similar to that of ordinary arrays by indexes.

struct Person {
    char name[50];
    int age;
    double height;
};

struct Person people[2];

As an example, let's create an array of structures that will store information about a person.

main.c

main.c

copy
12345678910111213141516171819202122232425262728293031323334353637
#include <stdio.h> #include <string.h> // structure definition struct Person { char name[50]; int age; double height; }; int main() { // declaring an array of structures struct Person people[3]; strcpy(people[0].name, "Alice"); people[0].age = 25; people[0].height = 1.75; strcpy(people[1].name, "Bob"); people[1].age = 30; people[1].height = 1.80; strcpy(people[2].name, "Charlie"); people[2].age = 35; people[2].height = 1.70; // output information about people from the array for (int i = 0; i < 3; ++i) { printf("Person %d:\n", i + 1); printf("Name: %s\n", people[i].name); printf("Age: %d\n", people[i].age); printf("Height: %.2f\n", people[i].height); printf("\n"); } return 0; }

Each element of the people array represents a separate Person structure. We can access the fields of a specific person using the array index, for example: people[0].name or people[1].age.

We then loop through the entire array using a for loop and print the information of each person to the screen.

Using arrays of structures allows you to store multiple objects of the same type in one place and easily access them by index, which is especially useful when working with large sets of data.

タスク

スワイプしてコーディングを開始

Implement a function calculateWarehouseTotal that computes the total value of all products stored in a warehouse. Each product has a name, quantity, and price. The function should iterate through the array of products and calculate the sum of quantity * price for all items.

  1. Inside the function calculateWarehouseTotal, create a variable total initialized to 0.0f.
  2. Use a for loop to iterate from index 0 to n.
  3. For each product, multiply quantity by price and add the result to total.
  4. Return the final value of total as the total warehouse cost.

解答

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

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

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

セクション 3.  4
single

single

AIに質問する

expand

AIに質問する

ChatGPT

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

some-alt