Pages

Friday, November 17, 2017

Easy tutorial for C / C ++ - struct 5 (Arrays of struct)

Easy tutorial for C / C ++ - struct 5 (Arrays of struct)

- Let's see how to apply a struct to an array. Three struct variables V_1, V_2, and V_3 were declared and initialized as follows.  

     t_Struct V_1 = {10, "orange", "red"};
     t_Struct V_2 = {20, "apple", "blue" };
     t_Struct V_3 = {30 , "banana", "white"};

- An array with the same contents as above can be displayed as follows.

     t_Struct V_a[3] = { {10, "orange", "red"},
                                     {20, "apple", "blue"},
                                     {30, "banana", "white"} };

- To access each element of a struct array, use subscripts in square brackets '[]' and use '.' operator. For example, to access the fruit name member variable of the second element, you would write: (V_a [1]. fruit)

- We confirmed earlier that the array name is the start address value of the array. The name of the struct array also represents the starting address value, and the next element can be accessed through the '+' operator. You can also use arrays of structs as arguments to functions.

- Let's look at an example.

Example Code

#include <iostream>
#include <iomanip>
using namespace std;

struct t_Struct{
   int num;
   char fruit[30];
   char color[30];
};

void C_A(t_Struct *,int);
int main() {

     t_Struct V_a[3] = { {10, "orange", "red"},
                         {20, "apple", "blue"},
                         {30, "banana", "white"} };

     t_Struct *pt;
     pt = V_a;

     C_A(pt,3);

     return 0;
}

void C_A(t_Struct *AA, int n)
{
     cout << setw(10) << "number";
     cout << setw(10) << "fruit";
     cout << setw(10) << "color";
     cout << endl;
    
     for(int i = 0; i < n; i++){
     cout << setw(10) << (AA+i)->num;
     cout << setw(10) << (AA+i)->fruit;
     cout << setw(10) << (AA+i)->color;
     cout << endl ;
          }
}

- We have declaraed the struct array 'V_a', the struct pointer variable 'pt' and function 'C_A'. Here, 'C_A' is a function that takes the number of elements of struct pointer variable and struct array as arguments and prints the value of each member variable. And we have accessed the member variable by using the pointer variable and the '->' operator.

- In the main function, we have declared a structure array 'V_a' and gave it initial values. We have declared the structure pointer variable 'pt' and assign the structure array name to 'pt'.

- The function 'C_A' was called with 'pt' and the number of elements in the array of structures as arguments.

results :

    number        fruit     color
            10    orange        red
            20      apple       blue
            30    banana     white

- You can see that the initial values of the struct array is printed.

No comments:

Post a Comment