Error in array in structure

The below given program shows the following error:
incompatible types in assignment of 'const char [12]' to 'char [25]'What does this error mean ?
Why is it coming
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;

struct date
{
int day;
int month;
int year;	
};

struct student
{
char name[25];
long int rollno;
date dob; 
};

int main()
{
//student a = {"Shivam Jain"};
student a;
a.name = "Shivam Jain"
a. rollno = 16530020;
a.dob.day = 1;
a.dob.month = 6;
a.dob.year = 1994; 
cout<<a.name<<endl;

return 0;	
}
Last edited on
It means that you can't use assignment when dealing with C-strings.

Can you please explain in some detail
Instead of:
char name[25];

use
std::string name;
If you use std::string you can use the = to assign a value. Note the header #include <string>

Also note the alternative way to initialise student b.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <string>

using namespace std;

struct date
{
    int day;
    int month;
    int year;
};

struct student
{
    string name;
    long int rollno;
    date dob; 
};

int main()
{
    student a;
    a.name      = "Shivam Jain";
    a.rollno    = 16530020;
    a.dob.day   = 1;
    a.dob.month = 6;
    a.dob.year  = 1994; 
    cout << a.name << endl;
    
    student b = {"Shivam Jain", 16530020, 1, 6, 1994 };
    cout << b.name << endl;
    
}


Or stay with the use of character arrays. Then you need the slightly different header #include <cstring> and you need the functions strcpy(), strcmp(), strcat() and so on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cstring>

using namespace std;

struct date
{
    int day;
    int month;
    int year;
};

struct student
{
    char name[25];
    long int rollno;
    date dob; 
};

int main()
{
    student a;

    strcpy(a.name, "Shivam Jain");
    a.rollno    = 16530020;
    a.dob.day   = 1;
    a.dob.month = 6;
    a.dob.year  = 1994; 

    cout << a.name << endl;
    
    student b = {"Shivam Jain", 16530020, 1, 6, 1994 };
    cout << b.name << endl;
}


http://www.cplusplus.com/reference/cstring/strcpy/

Usually in C++ the first approach using std::string is preferred - it is safer as well as more convenient to use.
closed account (48T7M4Gy)
long int rollno;

In the widesweep of things, avoiding problems with leading zeroes, searches etc it is not always a good idea to use integers. <string>'s or even c-style strings enable greater functionality in the long run.
Topic archived. No new replies allowed.