Search code examples
c++arraysstructassignment-operatorstring-literals

issue in intialising character array from the structure through an array object


i am getting an issue while initialising the character array in the structure through the structure object

#include <iostream>
    #include <string.h>
    using namespace std;
    struct emp
    {
        int age;
        char name[10];
    };
    int main()
    {
        struct emp v[2];
    
    List item
    
        v[0].age = 9;
        v[0].name[] = "name1"; <-this is where i am getting error
        v[1].age = 10;
        v[1].name[]= "name2"; <-this is where i am getting error
        for (int i = 0; i < 2; i++)
        {
            cout << v[i].age << " " << v[i].name<<endl;
        }
    
        return 0;
    }

Solution

  • For starters there is at least a typo

        v[0].name[] = "name1"; <-this is where i am getting error
                ^^^^ 
        v[1].name[]= "name2"; <-this is where i am getting error
                ^^^^
    

    Arrays do not have the assignment operator. So these assignment statements

    v[0].name[] = "name1";
    v[1].name[]= "name2"; 
    

    are incorrect syntactically and semantically.

    You could initialize the elements of the array when it is declared.

    For example

    struct emp v[2] =
    {
        { 9, "name1" },
        { 10, "name2" }
    };
    

    Otherwise you could use the standard string function strcpy. For example

    #include <cstring>
    
    //...
    v[0].age = 9;
    strcpy( v[0].name, "name1" );
    v[1].age = 10;
    strcpy( v[1].name, "name2" );
    

    Another approach is to use class std::string instead of the character array. For example

    #include <string>
    
    // ...
    struct emp
    {
        int age;
        std::string name;
    };
    
    int main()
    {
        struct emp v[2];
    
        v[0].age = 9;
        v[0].name = "name1";
        v[1].age = 10;
        v[1].name= "name2";
        for (int i = 0; i < 2; i++)
        {
            cout << v[i].age << " " << v[i].name<<endl;
        }
    
        return 0;
    }
    

    Pay attention to that instead of the ordinary for loop you could use the range-based for loop.

    For example

    for ( const auto &item : v )
    {
        cout << item.age << " " << item.name << endl;
    }