char array


1
2
3
4
5
6
7
8
9
10
11
  class student
{
   char name[4];
   int rno;
   public:
    student()
   {
     rno=1;  //valid
    name="abc";//it is not valid
}
};

the above statement will give an error.can we initialize char array in a constructor.
but the below code works well
1
2
3
4
5
6
7
8
       char *name;
       public:
      student()
{
       name="abc";
       rno=1;
}
  


what is the difference
Use strcpy to give some value to array char variable
1
2
char  name[4];
strcpy(name,"abs")


The second code works because
that is a pointer
when you use
 
name="abc";

compiler auto initializes name




Last edited on
As a matter of coding technique, when initializing data members of a class or struct within a constructor, it is always better to use an initializer list. In your case:

1
2
3
4
5
6
7
8
9
10
class student {
    char name[4];
    int    rno;

  public:
   student() : rno( 1 )   // Note initializer
   {
     // This one can't be in the initializer list.  Could be if name was a std::string instead  
     strncpy( name, sizeof( name ), "abc" );
   }
Topic archived. No new replies allowed.